[Tutor] searching a text file

Kent Johnson kent37 at tds.net
Wed Sep 5 13:33:37 CEST 2007


زياد بن عبدالعزيز الباتلي wrote:
> Alan Gauld wrote:
>> "Diana Hawksworth" <dianahawks at optusnet.com.au> wrote
>>
>>> How do I find a particular name, change the score and then save
>>> the changes back to the text file again??
>> iterate over the file checking (and modifying) each line
>> write the line back out:
>>
>> Pseudo code
>>
>> Out = open('foo.txt','w')
> BEWARE: this will truncate the file immediately, erasing all the data in 
> it!!!
> 
> Use a temporary file and after you finish processing the data in the 
> original file, move (or rename) the temporary file to the original name.

The fileinput module can help with this. It lets you edit a file 
line-by-line, in place, with a backup:
import fileinput
for line in fileinput.input('test.txt', inplace=1, backup='.bak'):
     if 'somestring' in line:
        line = 'I changed it\n'
     print line,

Kent


More information about the Tutor mailing list