我有一个带有交替名称和数字的.txt(从最低到最高排序的数字)。然后我有2个变量,一个整数和一个名字。 我想在.txt中搜索第一个数字> =到我的整数变量然后我想在我找到的数字上面写我的整数和名字(我需要它们在一个新行上,每个变量在一个单独的行上)。
这是我到目前为止所做的:
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)
这是正在搜索的测试.txt:
65
Munkshunk
164
Nimaman
649
Tila
891
Mugshoe
我想要最终看起来像这样:
65
Munkshunk
164
Nimaman
456
Georph
649
Tila
891
Mugshoe
但到目前为止,脚本只将我的2个变量附加到.txt 的末尾,如何将其插入到找到的变量之前的行?
答案 0 :(得分:1)
如果内存消耗和时间不是问题,最简单的方法是从文件读取所有数据,更改数据并用新数据覆盖文件:
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)
答案 1 :(得分:0)
对于任何想要使用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.