How to pass a substitution argument, e.g. * .txt in windows cmd

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)

At first I tried this on Linux, as you see that 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:

enter image description here

Of course, I can do it python test_fileinput.py 1.txt 2.txt, but I wonder if there is a way I could go on Windows? Thanks. *.txt

+4
source share
1 answer

You can use a module globthat provides a platform-independent way of matching wildcards. For example, it glob('*.txt')returns 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)

, ( python test_fileinput.py *.txt *.csv other.md ), :

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)
+5

Source: https://habr.com/ru/post/1526563/


All Articles