Using inputfile
from stdlib
There is one library in stdlib, which is often overlooked, called inputfile
.
It by default handles all input on command line or from stdin as filenames and allows iterating not only over those files, but also over all the lines in it, modifying them, decompressing and many other practical things.
filenames.py
- list all the filenames
import fileinput
for line in fileinput.input():
print "File name is: ", fileinput.filename()
fileinput.nextfile()
Call it:
$ python filenames.py *.txt
File name is: films.txt
File name is: highscores.txt
File name is: Logging.txt
File name is: outtext.txt
File name is: text.txt
upperlines.py
- print all lines from multiple files in uppercase
import fileinput
for line in fileinput.input():
print line.upper(),
and call it:
$ python upperlines.py *.txt
THE SHAWSHANK REDEMPTION (1994)
THE GODFATHER (1972)
THE GODFATHER: PART II (1974)
THE DARK KNIGHT (2008)
PULP FICTION (1994)
JAN HAS SCORE OF 101
PIETER HAS SCORE OF 900
CYRIL HAS SCORE OF 2
2014 APR 11 07:14:03.155 SECTORBLAH
INTERESTINGCONTENT
INTERESTING1 = 843
1. LUV_DEV <- HE'S A DEVELOPER
2. AMIT_DEV <- HE'S A DEVELOPER
....
upperlinesinplace.py
- turn all lines in files into uppercase
import fileinput
for line in fileinput.input(inplace=True):
print line.upper(),
Conclusions
fileinput
takes as default argument sys.argv[:1]
and iterates over all files and lines
- you can pass your own list of filenames to process
fileinput
allows inplace changing, filtering, reading file names, line numbers...
fileinput
even allows processing compressed files