2011-11-30 77 views
2

我正在运行一个在Windows上编译的Python程序,它接收文件作为输入,但在传递文件名时出现问题。如何从蟒蛇的cmd输入中提取文件名

foo.py:

def main(): 
    args = sys.argv[1:] 
    for i in args: 
    print i 

但是当我编译和从命令行调用它

\python foo.py *.html 

它直接给我的*.html的结果,我希望看到匹配的列表字符串。

任何人都熟知PLZ :)

+0

您正在使用什么壳呢?许多(如BASH)会在调用'python'之前自动将'* .html'扩展到匹配的字符串中。它的工作原理是 –

回答

4

你需要使用一种叫做glob的东西。对于单个文件名,你正在做的是好的。但是如果你想循环遍历一个文件模式,那么使用glob。它基本上是用于文件

import glob 

glob.glob('*.html') #return all html files in curr dir 
glob.glob('*')  # lists all files in the current directory python is running in 
glob.glob('*.jpg') # returns all jpeg images 
glob.glob('[a-z]????.*') # lists all files starting with a letter, followed by 4 characters (numbers, letters) and any ending. 

所以你的情况正则表达式 -

import glob 
def main(): 
    args = sys.argv[1:] 
    for file in glob.glob(args): 
     print i 
+0

。 Tkxxxxxxxxxxxxxxxxxxxx – user1038662

+0

@ user1038662很高兴与大家分享我的知识。如果此答案对您有帮助,请将其作为选定答案(左侧的绿色勾号)。帮助社区。谢谢。 –

0

使用glob模块将允许你形成正确的路径。