Python fileinput Module
Example
Iterate over lines from one or more files as a single stream:
import fileinput
import tempfile
import os
f1 = tempfile.NamedTemporaryFile(delete=False, mode="w", encoding="utf-8")
f1.write("Emil\nTobias\n")
f1.close()
count = 0
for line in fileinput.input(files=[f1.name]):
count += 1
print(count)
os.remove(f1.name)
Try it Yourself »
Definition and Usage
The fileinput module iterates over lines from stdin or a list of files.
Use it to treat multiple input files as a single stream and to get per-line metadata.
Members
Member | Description |
---|---|
filelineno() | Line number in the current file. |
filename() | Current filename (when iterating). |
input() | Return an iterator over lines from files or stdin. |
isfirstline() | Return True if the line is the first in the file. |
lineno() | Overall line number across all files. |