0

I have several files, and I need to replace third line in them:

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

What is the best way to do this?

Files are big enough, several 100mb's files.

Qiao
  • 16,565
  • 29
  • 90
  • 117

1 Answers1

1

I used this solution: 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')

But it does not work with files that contains non English 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>

That is bad. Where's python unicode? (file is utf8, python3).

File is:

фвыафыв
sdadf
试试
阿斯达а
阿斯顿飞
Community
  • 1
  • 1
Qiao
  • 16,565
  • 29
  • 90
  • 117
  • ok, it is bug http://stackoverflow.com/questions/6109022/unicodedecodeerror-while-using-cyryllic. Quite frustrating. – Qiao Nov 05 '11 at 10:09
  • you should use `open()` with `encoding='utf8'`. Feels good now :) – Qiao Nov 05 '11 at 10:15