我是Python新手,我正在用它来做一些数据分析。
我的问题如下:我有一个包含许多子目录的目录,每个子目录都包含大量数据文件。
我已经编写了一个 Python 脚本,当在这些子目录之一中执行时,该脚本会执行数据分析并将其写入输出文件。该脚本包含一些我调用的 shell 命令os.system()
,所以我必须“位于”子目录之一才能使其工作。
我怎样才能编写一个自动执行以下操作的函数:
- 移动到第一个子目录
- 执行脚本
- 返回上级目录并移动到下一个子目录
我想这可以通过使用某种方式来完成os.walk()
但我不太明白它是如何工作的。
PS我知道存在这个帖子 https://stackoverflow.com/questions/15005476/run-python-script-on-all-subdirectories-with-specific-name但这并不能解决我的问题。
PPS 也许我应该指出我的函数不将目录名称作为参数。其实这不需要争论。
要更改 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
- 改变你的working目录与os.chdir
单独使用 os.walk 是行不通的
我希望这有帮助!
祝你好运!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)