Gronk
Gronk

Reputation: 391

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?

Upvotes: 1

Views: 867

Answers (2)

Gronk
Gronk

Reputation: 391

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.

Upvotes: 0

rsk
rsk

Reputation: 1334

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)

Upvotes: 2

Related Questions