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 に答える