如何在特定行添加字符串
我有一个文件,里面有50行内容。我想用Python或者Linux的方法,在第20行加上一个字符串“-----”。
3 个回答
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的回答,详细内容可以在这里找到。
3
$ head -n 20 input.txt > output.txt
$ echo "---" >> output.txt
$ tail -n 30 input.txt >> output.txt
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。
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)