Writing to the previous line of a txt file in Python 3.3

I have a .txt with alternating names and numbers (the numbers ordered from lowest to highest). I then have 2 variables, an integer and a name. I want to search the .txt for the 1st number that is >= to my integer variable and then I want to write my integer and name above the found number (I need them on a new line, and each variable on a separate line).

This is what I have so far:

import re

new_num = 456
new_data = str(new_num) + '\n' + 'Georph'
written = False

with open('line_search.txt','r+') as f:
    data = f.readlines()
    for i, line in enumerate(data):
        number = (re.findall("\d+", line))
        if number:
            if new_num <= int(number[0]):
                while written == False:
                    written = True
                    print(number[0])
                    print("print 2 lines right before this line")
                    f.writelines(new_data)

And this is the test .txt being searched:

65
Munkshunk
164
Nimaman
649
Tila
891
Mugshoe

Which I want to end up looking like this:

65
Munkshunk
164
Nimaman
456
Georph
649
Tila
891
Mugshoe

But so far the script only appends my 2 variables to the end of the .txt, how do I make it insert it the line before the found variable?

Answers


If memory consumption and time is not a problem the easiest is to read all data from file, change data and overwrite file with new data:

import re

new_num = 456
new_data = str(new_num) + '\n' + 'Georph\n'
written = False

with open('line_search.txt','r') as f:
    data = f.readlines()
updated_data = []
for i, line in enumerate(data):
    if re.match("\d+", line):
        if new_num <= int(line):
            updated_data = data[:i] + [new_data] + data[i:]
            break
with open('line_search.txt', 'w') as f:
    f.writelines(updated_data)

For anyone who wants to use the fileinput method, here is what I came up with:

import re
import fileinput

new_num = 456
new_data = str(new_num) + '\n' + 'Georph'
written = False


for line in fileinput.input('line_search.txt', inplace=1):
    number = (re.findall("\d+", line))
    if number:
        if new_num <= int(number[0]):
            while written == False:
                written = True
                print(new_data)
    print(line.strip('\n')) #without the .strip('\n') the file get's re-written for some reason with a '\n' between every single line in the document.

Need Your Help

ssh "permissions are too open" error

permissions ssh

I had a problem with my mac where I couldn't save any kind of file on the disk anymore.

How to draw/overlay an image file to a bitmap image?

c# wpf image bitmap overlay

I have a video feed from a Kinect sensor hosted by an image stored as a bitmap. My question is how do I overlay an image, for example a .png on to the video feed.