replace a line in a text file

Sergey Krushinsky skru at ptc.ru
Fri Jun 11 11:09:27 EDT 2004


Larry Bates wrote:

>2) File isn't tremendously big, if it is you should
>use loop and xreadlines() to process one line at a
>time.
>
>  
>
Would you suggest using regular expressions in case of a large file? The 
first idea which came to my mind when I saw the Luis's question was:

import sys
import re

_FILENAME='test-1.txt'

p = re.compile('^(.*?4\.5.*?)$', re.MULTILINE)
f = open(_FILENAME, 'r')
old_txt = f.read()
f.close()
new_txt = p.sub('', old_txt)
open(_FILENAME, 'w').write(new_txt)

With best regards,
Sergey




More information about the Python-list mailing list