Reputation: 19328
My directory tree:
test/
|_____ 1.txt content: 1_line1\n1_line2
|_____ 2.txt content: 2_line1\n2_line2
|_____ test_fileinput.py
My Python script:
import fileinput
import sys
for line in fileinput.input(sys.argv[1:]):
print(fileinput.filename(), fileinput.filelineno(), line)
First I tried it on Linux, as you see it works flawlessly:
$ python3 test_fileinput.py *.txt
1.txt 1 1_line1
1.txt 2 1_line2
2.txt 1 2_line1
2.txt 2 2_line2
But on Windows:
Of course I can do python test_fileinput.py 1.txt 2.txt
, but I'm wondering is there a way that I could still pass *.txt
on Windows? Thank you.
Upvotes: 5
Views: 3558
Reputation: 64058
You could use the glob
module, which provides a platform-independent way of doing wildcard matching. For example, glob('*.txt')
would return a list of all txt files in the current directory.
import fileinput
import sys
from glob import glob
for line in fileinput.input(glob(sys.argv[1]):
print(fileinput.filename(), fileinput.filelineno(), line)
If you want to retain the behavior where you can specify multiple inputs (so that doing python test_fileinput.py *.txt *.csv other.md
would be valid behavior), you can modify your code the the following:
import fileinput
import sys
from glob import glob
all_files = [f for files in sys.argv[1:] for f in glob(files)]
for line in fileinput.input(all_files):
print(fileinput.filename(), fileinput.filelineno(), line)
Upvotes: 7