Newbie question: files..

Wesley C. wesc at rocketmail.com
Wed Oct 20 17:25:43 EDT 1999


In article <000601bf12db$2759d640$072d153f at tim>,
  "Tim Peters" <tim_one at email.msn.com> wrote:
> [Sonny Parlin]
> > I have a file of 1000 lines that I'm simply trying to read in and
display
> > using python. The code I have is here:
> >
> > #!/usr/bin/python
> >
> > file = open('testfile.txt', 'r')
> > for line in file.readlines(): # read file
> >     s = line[:-1] # get rid of newline
> >     print s #print string
> > file.close()


late reply here, but regarding files, there *are* multiple
ways to skin this cat.

sonny's first run at it:

file = open('testfile.txt', 'r')
for line in file.readlines(): # read file
    s = line[:-1] # get rid of newline
    print s #print string
file.close()

... opens the file, reads all the lines in, and prints
them one-at-a-time stripping the \n by slicing it.,
and the closing the file.

two things to note here that i didn't see in any of
the replies:

1) once f.readlines() completes, you can close the
   file right away instead of waiting (see below).

2) you can replace the stripping of \n and printing
   of 's' with a single line:  print s,
   the comma at the end means don't automatically add
   a \n... sorta like the Pascal write() and writeln()
   functions.

with those two (unrelated) changes, the program now
looks like:

file = open('testfile.txt', 'r')
lines = file.readlines(): # read file
file.close()
for eachLine in lines: # process each line
   print eachLine,      #print string

however, it's just as valid to process the entire file
as a single string, as in sonny's final example with
some motivation by jesse:

file = open('testfile.txt', 'r')
print file.read()
file.close()

print takes a string, and that's exactly what file.read()
does... it reads in the entire contents of the file into
a string object.  jesse's shorter 1-liner:

print open('testfile.txt').read()

...is fine too, although it's always a good idea to close
the file.  in this example, we've lost our file handle
and must wait for the garbage collector to cleanup after
us.  if the file is deleted while it is still opened, it
may still show up on a directory listing because the file
ref. count hasn't gone down to zero yet.


another way of doing it, which we haven't seen (probably
for good reason), is using file.readline():

file = open('testfile.txt', 'r')
while 1:
    line = file.readline(): # read line
    if not line: break  # empty string if EOF
    print line,    # print line
file.close()

we could've also used "if line == '': break" to check for
EOF.  when i was a Python newbie, i thought, wait a minute,
what if i really had a blank line or empty string in my
text file?  wouldn't this break out of displaying my file
prematurely?

the answer is no, because i totally forgot about the
embedded \n in my file.  an empty string would actually be
read as "\n", so the check for EOF (if '\n' == '') would
fail and everything would work properly!  just something
to keep in mind!


> >
> > I think I have some unnecessary steps in that program, because here
is the
> > Perl equivalent:
> >
> > #!/usr/bin/perl
> >
> > open(FD, "testfile.txt");
> > while(<FD>) {
> >     print $_;
> > }
> > close(FD);
> >
> > The Perl example is smaller and runs a few milliseconds faster, so
could
> > someone please point out the deficiencies in my python script?
>
> Your Perl is much too wordy <wink>:
>
> open(F,"testfile.txt");print <F>;
>
> Others will respond with trivial simplifications to the Python code
too, but
> who cares?  Nobody wins a Fabulous Prize for saving a keystroke.
>
> gotta-save-3-just-to-qualify-ly y'rs  - tim


nope, no one cares, except that seeing different ways of
doing the same thing with some commentary might be useful
to newbies.

here's my shortened Perl version  ;-)   ...

open(F, "testfile.txt");
print while(<F>);
close(F);

hope this helps!

-wesley

------------------------------------------------------------------------
"A computer never does what you want... only what you tell it."

Wesley C. <wesc at rocketmail.com>


Sent via Deja.com http://www.deja.com/
Before you buy.




More information about the Python-list mailing list