[Tutor] searching a text file
زياد بن عبدالعزيز البات
زياد بن عبدالعزيز البات
Wed Sep 5 12:55:10 CEST 2007
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.
> for line in file('foo.txt'):
> if 'somestring' in line:
> line = 'I changed it\n'
> Out.write(line)
>
> Out.close()
>
> You will find much more on this in my file handling topic in my
> tutorial.
>
>
Ziyad.
More information about the Tutor
mailing list