Loop many files in a folder and read them by line

I just make a example to explane how to use fileinput.

fileinput is use to loop some format files in a folder, and read it by lines.

The other ways also can to do this task. but fileinput is better. the old wany is use glob get all files then use open(filename) read it , then read it one by one line. or use os.walk to do it.

BUt fileinput is very sample to finish this task.

The example is following:

1
2
3
4
5
6
7
import fileinput
from glob import glob

for line in fileinput.input(glob(r'd:/*.txt')):
print "{} filename: {} lineno: {} linelength: {}".format(fileinput.lineno(),fileinput.filename(),fileinput.filelineno(),line.strip('/n'))

fileinput.close()

Note: afrer finished the read files. it must use fileinput.close() to close this internal object.