我有几个文件,我需要替换它们中的第三行:
files = ['file1.txt', 'file2.txt']
new_3rd_line = 'new third line'
这样做的最佳方式是什么?
文件足够大,有几个100mb的文件。
答案 0 :(得分:1)
我使用了这个解决方案:Search and replace a line in a file in Python
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replace_3_line(file):
new_3rd_line = 'new_3_line\n'
#Create temp file
fh, abs_path = mkstemp()
new_file = open(abs_path,'w')
old_file = open(file)
counter = 0
for line in old_file:
counter = counter + 1
if counter == 3:
new_file.write(new_3rd_line)
else:
new_file.write(line)
#close temp file
new_file.close()
close(fh)
old_file.close()
#Remove original file
remove(file)
#Move new file
move(abs_path, file)
replace_3_line('tmp.ann')
但它不适用于包含非英语字符的文件。
Traceback (most recent call last):
File "D:\xxx\replace.py", line 27, in <module>
replace_3_line('tmp.ann')
File "D:\xxx\replace.py", line 12, in replace_3_line
for line in old_file:
File "C:\Python31\lib\encodings\cp1251.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 32: character maps to <undefined>
这很糟糕。哪里的python unicode? (文件是utf8,python3)。
档案是:
фвыафыв
sdadf
试试
阿斯达а
阿斯顿飞