2012-12-14 45 views
1

我只想要以.jpg或.pdf結尾的文件名。我如何限制文件名搜索?僅限os.walk .jpg

import os 
from subprocess import call 

for dirname, dirnames, filenames in os.walk('.'): 
    for filename in filenames: 
     jpg = os.path.join(dirname, filename) 
     call(["./curl_recognize.sh", jpg, jpg+".txt", "-f txt"]) 
+0

另一種選擇是任意字符匹配可能在bash或其他東西中使用'find'和'-exec' –

回答

4

如何:

for filename in filenames: 
    if not filename.endswith('.jpg'): 
    continue 
0

如果你想在結束所有文件的列表,你可以做這樣的事情

filelist = [] 
for root, dirs, files in os.walk('.'): 
    filelist = filelist + [os.path.join(x,root) for x in files if x.endswith(('.jpg','.pdf'))] 
4
import fnmatch 
import os 

for file in os.listdir('.'): 
    if fnmatch.fnmatch(file, '*.txt'): 
     print file 

的fnmatch優於其他方法,因爲它假設unix像通配符,包括:

* =匹配一切

?=匹配任何單個字符

[SEQ] =匹配序列的任何字符

[!SEQ] =不SEQ