new linereading standard?

François Pinard pinard at iro.umontreal.ca
Wed Apr 26 09:45:11 EDT 2000


Johann Hibschman <johann at physics.berkeley.edu> writes:
> Robin Becker writes:

> > am I wrong for writing

> > for line in open('myfile.txt').readlines():
> >     print line

Under JPython (which I do not know), your file might stay opened until
the next garbage collection.  But I find the above writing so neat that
I prefer to rely on CPython reference counting, and consciously postpone
a lot of tedious rewriting if I ever have to use JPython.

All the clear writings which are allowed because reference counting are now,
for me, a strong source of Python addiction.  I feel ready to rely on it,
after I've been told that Python is going to stick with reference counting.

More to the specifics:

   for line in open('myfile.txt').readlines():
       print line

will give you a double spaced copy of your file, as `print' will add its own
newline after `line', which already has one.   You could write any of:

   for line in open('myfile.txt').readlines():
       print line,

   for line in open('myfile.txt').readlines():
       print line[:-1]

   for line in open('myfile.txt').readlines():
       print line[:-len(os.linesep)]

depending on taste, the system you are using, and the fact that the last
line is terminated or not.  Getting simpler and faster, you might try:

   for line in open('myfile.txt').readlines():
       sys.stdout.write(line)

   sys.stdout.writelines(open('myfile.txt').readlines())

   sys.stdout.write(open('myfile.txt').read())

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list