在特定行插入文本python

2024-09-22 14:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码在一行中插入文本:

exp = 82
with open ('test.txt','r') as b:
    lines = b.readlines()
with open('test.txt','w') as b:
    for i,line in enumarate(lines):
        if i == exp:
            f.write('test_data')
        f.write(line)

这将在第82行插入文本。如何修改它,使它可以在第82行插入文本,当它第一次运行时,在第83行,然后在第84行等等。我想使用一个计数器,但我不确定。在


Tags: 代码intest文本txtforifas
3条回答

如果不想完全循环该文件,可以使用以下命令:

#!/usr/bin/python

exp = 5
seq = ["This is new line\n","This is new line\n"]
# Open a file
fo = open("foo.txt", "r+b")

lngth = 0
#count the number of char until the desired line
for i in range(1,exp):
    line = fo.readline()
    lngth = len(line) + lngth
# read the rest of the file
lines = fo.read()
# go back to insert position
fo.seek(lngth, 0)
# insert sequence in file
fo.writelines(seq)
# write rest of the file
fo.write(lines)
# Close opend file
fo.close()

对于原始测试输入:

^{pr2}$

我得到了以下信息:

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is new line
This is new line
This is 5th line
This is 6st line
This is 7nd line
This is 8rd line
This is 9th line
This is 10th line

如果您有一个巨大的文件,您无法将其加载到RAM中(请参见阅读)您可能希望使用其他一些解决方案进行枚举和逐行处理。 希望这有帮助!在

方法是增加一个计数器。在

counter = exp
stop = 90
with open('test.txt', 'w') as b:
     for i, line in enumerate(lines):
           if i == counter and i != stop:
               b.write('test_data')
               b.write(line)
           else:
                break
           counter += 1

您可以使用文本文件来存储代码已经运行了多少次。从文本文件中读取此值并将其添加到ex中。然后增加代码运行的次数,将其写入文本文件,然后运行您编写的代码。在

counterFile = open("counter.txt","r") #counter.txt stores the number of times code has been run. Just create this file manually
counter = counterFile.read()
if(len(counter) == 0):
    counter = 0
else:
    counter = int(counter)
counterFile.close()

exp = 0
with open ('test.txt','r') as b:
    lines = b.readlines()
with open('test.txt','w') as b:
    for i,line in enumerate(lines):
        print i
        if i == exp+counter:
            b.write('test_data\n')
        b.write(line)

counter += 1
counterFile = open("counter.txt","w")
counterFile.write(str(counter))
counterFile.close()

相关问题 更多 >