2013-05-08 61 views
0

我大約有100個文件存儲在不同的目錄中。我寫了一個腳本,但是目前我正在爲所有這些文件一次運行這個腳本。我知道如果我將這些文件保存在一個目錄中,我可以使用os.chdir,os.listdir一個接一個地運行它們。 但是,對於我將它們移動到一個目錄不是一個選項。 有沒有辦法按順序連續執行所有這些文件,並讓我的生活更輕鬆?在不同的目錄中執行類似的文件python

+0

你真的是指「執行」還是「過程」? – Alfe 2013-05-08 12:50:19

回答

1

您可以使用一般爲os.walk這種事情:

import os 
for root, dirs, files in os.walk(os.path.abspath("/parent/dir/")): 
    for file in files: 
    if os.path.splitext(file)[1] == '.py': 
     print os.path.join(root, file) 

還與fnmatch很好地工作:

import os 
import fnmatch 

for root, dirnames, filenames in os.walk("/parent/dir/"): 
    for filename in fnmatch.filter(filenames, '*.py'): 
    # do your thing here .. execfile(filename) or whatever 
0

我有點困惑。如果你想改變當前目錄(大概是因爲你的函數使用相對路徑)做這一切從蟒之內:

directory_list = [ ... ] #list of directories. You could possibly get it from glob.glob 
here = os.getcwd() #remember the "root" directory 
for directory in directory_list: 
    os.chdir(directory) #change to the "work" directory 

    #do work in "work" directory 

    os.chdir(here) #go back to the root directory 

當然,如果你已經有了劇本克隆到你的100個目錄,那麼你就可以只需通過bash運行它:

for DIR in directory_glob_pattern; do cd $DIR && python runscript.py && cd -; done 
相關問題