[Tutor] file I/O

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 12 Jul 2001 08:48:04 +0200


On  0, steve <lonetwin@yahoo.com> wrote:
> 	I've been meaning to ask this question for a long time now,
> I've always seen ppl do file i/o, especially file read using an open() 
> followed by a loop of readline(), stripping the '\n' at the end....
>   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 ???

Well, not a bad thing, but I think you lose most of the advantages of
fileinput (not reading in the whole file at once, for one). On the other
hand, fileinput will probably give a small performance hit because it has to
supply these things, and the strip() in the list comprehension are minor
slowdowns as well.

If you need the whole file in lines, but without \n, the easiest way is to
read it all in and to split on \n:

p = open("myfile.txt","r").read().split("\n")

That's the most direct way.

-- 
Remco Gerlich