简体   繁体   English

在Python 3.3中写入txt文件的上一行

[英]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). 我有一个.txt,其中包含交替的名称和数字(数字从最低到最高排序)。 I then have 2 variables, an integer and a name. 然后,我有2个变量,一个整数和一个名称。 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). 我想在.txt中搜索第一个数字,该数字> =我的整数变量,然后我将我的整数和名称写在找到的数字之上(我需要在新行中将它们和每个变量都在单独的行中) 。

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: 这是正在搜索的测试.txt:

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? 但是到目前为止,脚本仅将我的2个变量附加到.txt的末尾 ,如何使它在找到的变量之前插入它?

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: 对于任何想使用fileinput方法的人,这是我想出的:

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM