[Tutor] reading file, adding to each line, writing file

David ldl08 at gmx.net
Wed Feb 4 17:11:41 CET 2009


Hello Arthur,

not there yet....

A.T.Hofkamp wrote:
>
> The simplest solution would be to construct a new line from the old 
> one directly below the 'while', for example
>
> line2 = line[:-1] + " -d\n"
>
> followed by writing line2 to disk. 
Actually, I don't quite understand. You want me to put
line2 = line[:-1] + " -d\n"
right beneath the 'while', that is, without indenting it?? Never seen 
that before...

Here is my latest try, which works:

# add " -d" to each line of a textfile

infile = open("step3", 'r') # open file for appending -- returns a file 
object
outfile = open("pyout","a") # open file for appending -- returns a file 
object

line = infile.readline()    # Invokes readline() method on file
for i in line:
    line2 = line[:-1] + " -d\n"
    outfile.write(line2),     # trailing ',' omits newline character
    line = infile.readline()
      
infile.close()
outfile.close()
print "done!"

But I clearly still don't understand my own code.
In particular I don't understand why I have to use infile.readline() 
twice, once before the for loop, and once inside it.
Finally: changing the line "for i in line:" for "while line:" will 
freeze the machine, filling my hard disk.

Any ideas?

David




More information about the Tutor mailing list