[Tutor] reading lines from a list of files

David Rock david at graniteweb.com
Tue May 12 18:12:04 CEST 2015


* Alex Kleider <akleider at sonic.net> [2015-05-12 02:33]:
> On 2015-05-11 23:48, Peter Otten wrote:
> > Alex Kleider wrote:
> > 
> >> Is there a better (more 'Pythonic') way to do the following?
> >> 
> >>      for f_name in f_names:
> >>          with open(f_name, 'r') as f:
> >>              for line in f:
> > 
> > There's the fileinput module
> > 
> > <https://docs.python.org/dev/library/fileinput.html#fileinput.input>
> > 
> > but personally I prefer the way you show above.
> 
> Then I'll stick with what you prefer and what I know.
> It seems silly to import yet another module for the sole
> purpose of saving one line of code although the reason
> for my inquiry was more to diminish levels of indentation
> than number of lines.
> Thanks,
> Alex

Personally, *I* prefer fileinput as my go-to file reader.

Don't knock fileinput for "saving one line." It does a lot more than
that.  It allows your script to manage the filelist as an input,
automatically handles stdin so your script can easily be both a filter
in a pipeline and a file reader, plus a host of other useful methods for
info about the file you are reading.

Part of what you really need to define is the context of your question
of "better."  What is your use case?  From where is your list of files
coming?  Is it truly just "read and forget"?  Your needs will dictate
what option is "best."  It may be what you've already done yourself, it
may be fileinput, or it may be something completely different.

-- 
David Rock
david at graniteweb.com


More information about the Tutor mailing list