我有一个包含50行的文件。如何使用python / linux在第20行添加字符串“-----”到特定行?
答案 0 :(得分:5)
你尝试过这样的事吗?:
exp = 20 # the line where text need to be added or exp that calculates it for ex %2
with open(filename, 'r') as f:
lines = f.readlines()
with open(filename, 'w') as f:
for i,line in enumerate(lines):
if i == exp:
f.write('------')
f.write(line)
如果您需要编辑差异行数,可以通过以下方式更新代码:
def update_file(filename, ln):
with open(filename, 'r') as f:
lines = f.readlines()
with open(filename, 'w') as f:
for idx,line in enumerate(lines):
(idx in ln and f.write('------'))
f.write(line)
答案 1 :(得分:3)
$ head -n 20 input.txt > output.txt
$ echo "---" >> output.txt
$ tail -n 30 input.txt >> output.txt
答案 2 :(得分:0)
如果要读取的文件很大,并且您不想一次读取内存中的整个文件:
from tempfile import mkstemp
from shutil import move
from os import remove, close
line_number = 20
file_path = "myfile.txt"
fh_r = open(file_path)
fh, abs_path = mkstemp()
fh_w = open(abs_path, 'w')
for i, line in enumerate(fh_r):
if i == line_number - 1:
fh_w.write('-----' + line)
else:
fh_w.write(line)
fh_r.close()
close(fh)
fh_w.close()
remove(file_path)
move(abs_path, file_path)
注意:我使用Alok的回答here作为参考。