[Tutor] Reading a file
Alan Gauld
alan.gauld at btinternet.com
Fri Jul 2 20:27:50 CEST 2010
"David Hutto" <smokefloat at gmail.com> wrote
> In the code below, I'm trying to read from a file, and print out the
> lines.
Steven addressed that but...
> def increment():
> for number in range(1, 500):
> print number ++1
This function if called will print out all of the numbers at once, it
won't return anything.
I don't think thats what you want. Maybe it was:
def increment()
for number in range(500)
yield number + 1 # returns the numbers 1.....500, one
number per call.
There are better ways to do that but this was the nearest guess
I could make to your possible intent...
> readcont = linecache.getline(outputfile, increment) '''increment is
Here you pass the name of the function increment, I suspect
that you meant to do
readcont = linecache.getline(outputfile, increment() )
where increment was like the generator function above.
However even if you did want to do that using enumerate() would
probably be more effective. So slightly mofdifying Steven's code:
f = open("filename.txt")
for number, line in enumerate(f):
print "%5d%s" % (number, line)
f.close()
Is that close?
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list