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

2024-06-06 22:35:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

如何编写一个自动:

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

我想这可以用os.walk()以某种方式完成,但我并不真正理解它是如何工作的。

我知道this post的存在,但它并不能解决我的问题。

PPS也许我应该指出我的函数没有把目录名作为参数。实际上不需要争论。


Tags: 文件函数命令目录脚本os数据文件方式
3条回答

要在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

我不知道你的剧本是怎么写的,因为你的问题很笼统,所以我只能给出一个笼统的答案。。。。

但我想你需要的是:

  1. 获取所有子目录并使用os.walk
  2. os.chdir更改工作目录

操作系统。单独行走不起作用

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

这样就可以了。

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(子目录的列表)感兴趣,所以要索引[1]。

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循环中执行分析。添加分析代码,以便for循环不仅仅打印内容。

相关问题 更多 >