[英]How to add a string to a specific line
I have a file which contains 50 lines. 我有一个包含50行的文件。 How can i add a string "-----" to a specific line say line 20 using python/linux ?
如何使用python / linux将字符串“-----”添加到特定行,如第20行?
Have you tried something like this?: 你尝试过这样的事吗?:
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)
If you need to edit diff number of lines you can update code above this way: 如果您需要编辑差异行数,可以通过以下方式更新代码:
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)
$ head -n 20 input.txt > output.txt
$ echo "---" >> output.txt
$ tail -n 30 input.txt >> output.txt
If the file to read is big, and you don't want to read the whole file in memory at once: 如果要读取的文件很大,并且您不想立即读取内存中的整个文件:
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)
Note: I used Alok's answer here as a reference. 注意:我在这里使用Alok的答案作为参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.