[Tutor] file I/O

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 12 Jul 2001 10:29:09 -0700 (PDT)


On Thu, 12 Jul 2001, steve wrote:

>   I discovered fileinput (the module) quite early on when I started learning 
> python....so I always do things like
> 
> Python 2.1 (#3, Jun 25 2001, 13:39:27) 
> [GCC 2.95.3 19991030 (prerelease)] on linux2
> Type "copyright", "credits" or "license" for more information.
> >>> import fileinput
> >>> p = [ line.strip() for line in fileinput.input("myfile.txt") ]
> 
> 	What bothers me is that I don't see enough ppl do that, an' I
> wonder is it b'cos it is some kinda *Bad thing* ....could n e one
> comment on this ???

[warning: advanced apologies for the coding style.]



The fileinput module itself isn't bad: if you have familiarity with the
Perl programming language, you might recognize fileinput as an analog to
the magic '<>' operator.  When using fileinput.input(), we can actually
leave it's input argument blank.  To show this, let's make a fast
'one-liner' program.

###
import fileinput; print ''.join([l.strip() for l in fileinput.input()])
###

This one-liner program takes any text file, and turns it into one long
line.  As we can see, there's no filename involved: fileinput()'s
usefulness comes from the fact that it will automagically look for its
input from filenames given at the prompt or standard input.  Here are a
few sample runs:


###
[dyoo@tesuque dyoo]$ python makeOneLiner.py 
hello world
this is a test
of the emergency broadcast
system.
                  [At this point, I press Ctrl-d a few times to indicate
                   the end of input.]
hello worldthis is a testof the emergency broadcastsystem.


[dyoo@tesuque dyoo]$ cat foo.txt
hello again
This is a another test of the emergency
broadcast system.
[dyoo@tesuque dyoo]$ python makeOneLiner.py foo.txt
hello againThis is a another test of the emergencybroadcast system.
###


This obscure program makes everything hard to read.