[Tutor] reading file, adding to each line, writing file
Alan Gauld
alan.gauld at btinternet.com
Wed Feb 4 22:51:27 CET 2009
"David" <ldl08 at gmx.net> wrote
> Here is my latest try, which works:
>
> # add " -d" to each line of a textfile
>
> infile = open("step3", 'r')
> outfile = open("pyout","a")
>
> line = infile.readline() # Invokes readline() method on file
line is now a string representing a line in the file.
> for i in line:
You are now iterating over every character in line
> line2 = line[:-1] + " -d\n"
So you repeat this assignment for every character.
No harm done its the same every time. Just very inefficient!
> outfile.write(line2), # trailing ',' omits newline character
But you are writing the same line for every character - did
you find lots of duplicate lines in the output?
> line = infile.readline()
And now you reset line to the next line so invalidating some
of what I njust said. I doubt this actually works properly although
it may appear to!
The use of the for loop is much simpler, avoiding all the
readline confusion:
infile = open("step3", 'r')
outfile = open("pyout","a")
for line in infile: # no need for readline
outfile.write(line.rstrip() + " -d\n")
infile.close()
outfile.close()
print "done!"
That's all you need!
for loops reading direct from the file are ideally suited to this
kind of program and indeed any situation where you are
handling a fixed size input.
while loops are better for when you don't know where the
end will be or even if there will be an end!
HTH,
Alan G.
More information about the Tutor
mailing list