Python:运行所有子目录中的脚本

val*_*rio 5 python

我是Python新手,我正在用它来做一些数据分析。

我的问题如下:我有一个包含许多子目录的目录,每个子目录都包含大量数据文件。

我已经编写了一个 Python 脚本,当在这些子目录之一中执行时,该脚本会执行数据分析并将其写入输出文件。该脚本包含一些我称为 using 的 shell 命令os.system(),因此我必须“位于”子目录之一才能使其工作。

我怎样才能编写一个自动执行以下操作的函数:

  1. 移动到第一个子目录
  2. 执行脚本
  3. 返回上级目录并移动到下一个子目录

我想这可以通过某种方式来完成os.walk(),但我不太明白它是如何工作的。

PS 我知道这篇文章的存在,但它并没有解决我的问题。

PPS 也许我应该指出我的函数不将目录名称作为参数。其实这不需要争论。

ant*_*isk 3

要更改 Python 中的工作目录,您需要:

os.chdir(your_path)
Run Code Online (Sandbox Code Playgroud)

然后您可以递归运行脚本。

示例代码:

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
Run Code Online (Sandbox Code Playgroud)

我不知道你的脚本是如何工作的,因为你的问题很笼统,所以我只能给出一个笼统的答案......

但我认为你需要的是:

  1. 使用 os.walk获取所有子目录并存储它们
  2. 使用os.chdir更改您的工作目录

单独使用 os.walk 是行不通的

我希望这有帮助!祝你好运!