[Tutor] Reading a file

Steven D'Aprano steve at pearwood.info
Fri Jul 2 17:31:22 CEST 2010


On Fri, 2 Jul 2010 11:16:02 pm David Hutto wrote:
> In the code below, I'm trying to read from a file, and print out the
> lines. 

f = open("filename.txt")
for line in f:
    print line
f.close()

is all you need, and even the close at the end is optional (but 
recommended).


> I know I've seen the exact function I'm looking for here, but 
> it seems like the below 'should' work.
>
> The second function(rdfil) works, if just the line number is placed
> there, and th first(increment) works for printing a new number in
> range for the rdfil to operate while going through the lines in the
> file.
> Any other options other than using linecache.getline(I'm sure there
> are, just haven't jogged the right memory cell loose yet)?
>
> def increment():
> 	for number in range(1, 500):
> 		print number ++1

Why do you have number ++1 instead of just number+1 ?

For that matter, why do you have number+1 instead of changing the range 
to range(2, 501)?


> def rdfil():
> 	outputfile = raw_input('Input file name: ')

This puts a *string* in the variable outputfile. A better name would 
be "outputfilename", because it is a file NAME, not a file.

> 	for line in outputfile:

This is terribly misleading, because iterating over a string gives you 
the individual characters of the string, not lines. E.g.:

for line in "file.txt":
    print line

will print:

f
i
l
e
.
t
x
t

> 		if line:

This will always be true, and so is pointless. Even an empty line is not 
truly empty, as it will be a newline character. When the file is empty, 
the for-loop will exit.

> 			readcont = linecache.getline(outputfile, increment) '''increment
> is originally supposed to be an int for the line number being read'''

This line gives a syntax error. What is it supposed to be? What is the 
purpose of the string? It looks like it is meant to be a comment, but 
why have you written it as a string instead of a # comment?


-- 
Steven D'Aprano


More information about the Tutor mailing list