3

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.

4

1 回答 1

5

我不太确定最初的示例应该是什么,但要从标准 Windows 命令提示符执行此操作,您可以使用以下内容:

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

如果你做这样的事情,你的代码中需要类似下面的内容:

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

或者,您可以考虑使用该fileinput模块来获取第二个示例中的文件列表并处理它们。也就是说,在您的脚本中,您将拥有如下内容:

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

或者您可以将通配符表达式作为参数并使用该glob模块,这样您就可以运行:

python my_script.py FY*.txt

然后在您的脚本中执行以下操作:

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

glob 可以在多个参数上运行:

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)

这将允许您执行:

python my_script FY*.txt WS*.txt
于 2012-08-09T16:23:09.797 回答