我有一个包含 50 行的文件。如何使用 python/linux 将字符串“-----”添加到特定行,比如第 20 行?
问问题
4266 次
3 回答
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)
于 2013-03-06T03:25:53.917 回答
3
$ head -n 20 input.txt > output.txt
$ echo "---" >> output.txt
$ tail -n 30 input.txt >> output.txt
于 2013-03-06T03:27:51.840 回答
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 的答案作为参考。
于 2013-03-06T03:54:08.227 回答