Newbie question: files..

Jesse D. Sightler jsight at mindspring.com
Sun Oct 10 02:56:18 EDT 1999


Hi Sonny,

Sonny Parlin wrote:
> 
> Hello, I'm trying to learn python by setting up some pretty easy examples
> of file manipulation...
> 
> 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()

Or you could just do 
  print open ('testfile.txt').read()

See, it's a one liner!  :-)  Similarly, you could simply replace the two
lines in the for loop with the one statement:
  print line[:-1]

> 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?

Python is frequently slightly slower than Perl.  However, you should
note that at the very least the Python code is the same number of lines
(or fewer using my version:), and doesn't have the silly unnamed
variables or ludicrous use of file descriptors.  Python still rules. :)

-- 
---------------
Jesse D. Sightler
http://www.biddin.com/delorean




More information about the Python-list mailing list