2011-11-05 151 views
0

我有几个文件,我需要更换三线在其中:替换文件指定行在Python

files = ['file1.txt', 'file2.txt'] 
new_3rd_line = 'new third line' 

什么是做到这一点的最好方法是什么?

文件足够大,几个100MB的文件。

+0

你会喜欢它时,有一个空文件,或者只有一个文件一行吗? – MoshiBin

+2

什么最好?速度/可伸缩性(如何做这10万次)灵活性(如何取代第10,000条线)?记忆? (在4GB日志文件上执行此操作)?需要呻吟信息。 – Triptych

+0

我厌倦了'用文件计算器中的行',保存每一行'if counter == 3',但我想看到或多或少的最佳方式。 – Qiao

回答

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') 

但它不包含非英语charecters文件。

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 
试试 
阿斯达а 
阿斯顿飞 
+0

好的,这是错误http://stackoverflow.com/questions/6109022/unicodedecodeerror-while-using-cyryllic。非常令人沮丧。 – Qiao

+0

你应该使用'open()'和'encoding ='utf8''。现在感觉很好:) – Qiao

+0

+ Intresting错误:) – Baba