我有一个文件-
First Line
Second Line
Third Line
Fourth Line
Fifth Line
Sixth Line
现在,我想在第四行之后写入文件的内容。 因此新文件将是-
Fifth Line
Sixth Line
我的尝试-
cnt=0
for root, dirs, files in os.walk(currentdir):
for name in files:
f = open(root+"/"+name,'r')
lines = f.readlines()
f.close()
f = open(os.path.join(root, name),"w")
for line in lines:
cnt+=1
if line =="fourth Line"+"\n":
break:
f.seek(cnt)
f.write(line)
f.close()
答案 0 :(得分:1)
for path, dirs, files in os.walk(currentdir):
for name in files:
with open(os.path.join(path, name)) as f:
data = f.readlines()
pos = data.index("Fourth Line\n")
with open(os.path.join(path, name), 'w') as f:
f.writelines(data[pos:])
答案 1 :(得分:1)
您只需将行存储在文件中,对数组进行切片,然后将其写回:
with open('filename.txt', 'r+') as f:
lines = f.readlines()
f.write(lines[5:])
如果需要,可以在单独的with
块中或在其他任何块中进行读写。
答案 2 :(得分:0)
您可以将文件行加载到列表中,然后在拆分列表后仅保留所需的行并保存在文件中。例如,如果您想要第四行之后的内容:
f = open("file.txt", 'r')
lines = f.readlines()
f.close()
lines = lines[4:]
f = open("file.txt", 'w')
f.write(lines)
f.close()
答案 3 :(得分:0)
您总是可以将一个计数器放在循环中,并在计数器达到4时开始写第二个文件。
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
或:
f1 = open(path, 'w')
f1.write(data)
f1.close()
counter += 1
if counter >= 4:
f2 = open(path, 'w')
f2.write(data)
f2.close()