[英]Python: run script in all subdirectories
我是 Python 的新手,我用它來做一些數據分析。
我的問題如下:我有一個包含許多子目錄的目錄,每個子目錄都包含大量數據文件。
我已經編寫了一個 Python 腳本,當在其中一個子目錄中執行時,它會執行數據分析並將其寫入 output 文件。 該腳本包括一些我使用os.system()
調用的 shell 命令,因此我必須“位於”其中一個子目錄中才能正常工作。
我怎樣才能寫一個 function 自動:
我想這可以使用os.walk()
以某種方式完成,但我並不真正理解它是如何工作的。
PS 我知道這篇文章的存在,但它並沒有解決我的問題。
PPS 也許我應該指出我的 function 沒有將目錄名作為參數。 實際上它不需要爭論。
os.walk應該可以完美地完成您想做的事情。 開始使用此代碼,您應該看到需要做的事情:
import os
path = r'C:\mystartingpath'
for (path, dirs, files) in os.walk(path):
print "Path:", path
print "\nDirs:"
for d in dirs:
print '\t'+d
print "\nFiles:"
for f in files:
print '\t'+f
print "----"
該代碼將執行的操作是向您顯示os.walk將遍歷所選起始路徑的所有子目錄。 進入每個目錄后,可以通過將路徑和文件名連接起來來獲得每個文件名的完整路徑。 例如:
path_to_intersting_file = path+'\\'+filename
# (This assumes that you saved your filename into a variable called filename)
使用每個文件的完整路徑,您可以在os.walk for loop中執行分析。 添加您的分析代碼,以便for循環所做的不僅僅是打印內容。
要在Python中更改工作目錄,您需要:
os.chdir(your_path)
然后,您可以遞歸運行腳本。
示例代碼:
import os
directory_to_check = "your_dir" # Which directory do you want to start with?
def my_function(directory):
print("Listing: " + directory)
print("\t-" + "\n\t-".join(os.listdir("."))) # List current working directory
# Get all the subdirectories of directory_to_check recursively and store them in a list:
directories = [os.path.abspath(x[0]) for x in os.walk(directory_to_check)]
directories.remove(os.path.abspath(directory_to_check)) # If you don't want your main directory included
for i in directories:
os.chdir(i) # Change working Directory
my_function(i) # Run your function
我不知道您的腳本如何工作,因為您的問題很籠統,所以我只能給出一個籠統的答案。
但我認為您需要的是:
單獨的os.walk無法正常工作
我希望這有幫助! 祝好運!
這樣可以完成。
for dir in os.listdir(your_root_directory):
yourFunction(dir)
os.listdir
方法僅返回根目錄中的目錄列表。
但是, os.walk
方法以遞歸方式遍歷目錄,這使其對其他事情有用,並且os.listdir
可能更好。
但是,為了完整起見,這是一個os.walk
選項:
for dir in next(os.walk(your_directory))[1]:
yourFunction(dir)
注意os.walk
是一個生成器,因此是下一個調用。 第一個下一個調用將生成一個元組根目錄,dirs文件。 在這種情況下,根目錄是您的目錄。 您只對dirs-子目錄列表感興趣,因此可以索引[1]。
如果要對文件夾的每個子文件夾執行特定操作,一種方法是編寫一個遞歸函數,一次處理每個目錄。 希望我的示例對您有所幫助: http : //pastebin.com/8G7JzcQ2
我在做類似的事情, cd
進入每個子目錄並運行git
命令等。縮短版本
import os
import pathlib
import subprocess
if __name__ == "__main__":
# dir path of a script, subdirectories are here
ROOT_PATH = os.getcwd()
# all files, folders in script's directory
for name in os.listdir(ROOT_PATH):
dir_path = os.path.abspath(name)
# if a subdirectory
if os.path.isdir(dir_path):
# cd to subdirectory
os.chdir(dir_path)
# could run a script subprocess.run(["python", "my_script.py"])
# or you could run all commands here one by one
git_log = subprocess.getoutput(['git', 'log', '-n1'])
print(git_log + "\n")
# move back to script's dir
os.chdir(ROOT_PATH)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.