Snaaa
Snaaa

Reputation: 256

Running python from windows command prompt on many files

This is a stupid question, and I know it is, but for some reason I can't find any useful tutorials for running python from windows command prompt so I'll have to ask you guys. I have a script I need to run on all files starting FY*.txt or WS*.txt in one directory. I've tried going to the directory through command prompt and doing

for file in FY*.txt; do python my_script.py

which just informs me that 'file' is unexpected at this time. I've also tried

python my_script.py FY1.txt FY2.txt FY3.txt

with

import sys
inputfilenames=sys.argv[1:27]

for name in inputfilenames:
    datafile=open(name,'r')

as the way I open my files in the python script itself. This seems to only run the script on one file, rather than all of them.

I apologise for my ignorance, I really have no clue how to use command prompt to run python things. As well as answers, if anyone has any tutorial recommendations I would be very, very grateful.

Upvotes: 3

Views: 1802

Answers (1)

ig0774
ig0774

Reputation: 41257

I'm not quite certain what that initial example is supposed to be, but to do that from the standard Windows command prompt, you could use something like this:

for %G in (FY*.txt); do python my_script.py %G

If you do something like this, you'll need something like the following in your code:

with open(sys.argv[1], 'r') as f:
    do_something_with(f)

Alternatively, you could look into using the fileinput module to take a list of files as in your second example and process them. That is, inside your script you'd have something like:

for line in fileinput.input():
    do_something_with(line)

Or you could make the wildcard expression an argument and use the glob module, so you could run:

python my_script.py FY*.txt

And then in your script do something like:

for file in glob.glob(sys.argv[1]):
     with open(file, 'r') as f:
         do_something_to(f)

The glob could be run over multiple arguments:

for files in([glob.glob(arg) for arg in sys.argv[1:]]):
    for file in files:
        with open(file, 'r') as f:
            do_something_to(f)

which would allow you to execute:

python my_script FY*.txt WS*.txt

Upvotes: 5

Related Questions