我是Python的新手,正在使用它进行一些数据分析。
我的问题如下:我有一个包含许多子目录的目录,每个子目录都包含大量的数据文件。
我已经编写了一个Python脚本,当在这些子目录之一中执行该脚本时,它将执行数据分析并将其写入输出文件中。该脚本包含一些我使用调用的shell命令os.system()
,因此我必须在其中一个子目录中“成为”它才能工作。
如何编写自动执行的功能:
我想可以使用某种方式完成此操作,os.walk()
但我并不十分了解它是如何工作的。
PS我知道这篇文章的存在,但不能解决我的问题。
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无法正常工作
我希望这有帮助!祝你好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句