【问题标题】:Iterate over files in multiple directories or an entire hard drive in python在 python 中迭代多个目录或整个硬盘驱动器中的文件
【发布时间】:2015-01-03 14:43:38
【问题描述】:

我有 script.py 文件,它遍历 script.py 文件所在目录中的特定文件。

脚本看起来像这样:

def my_funct(l):
     Does stuff:
          iterates over list of files
     Does stuff:
globlist = glob.glob('./*.ext')
my_funct(glob list)

我希望不仅能够迭代此目录中的 *.ext 文件,还希望能够迭代此目录中所有目录中的所有 .ext 文件。

我正在阅读的有关 os.walk 的信息没有意义。

谢谢。

【问题讨论】:

标签: python operating-system glob


【解决方案1】:

os.walk 的一个例子。它在文件夹(和所有子文件夹)中搜索 py 文件并计算行数:

# abspath to a folder as a string
folder = '/home/myname/a_folder/'
# in windows:
# folder = r'C:\a_folder\'
# or folder = 'C:/a_folder/'

count = 0
lines = 0
for dirname, dirs, files in os.walk(folder):
    for filename in files:
        filename_without_extension, extension = os.path.splitext(filename)
        if extension == '.py':
            count +=1
            with open(os.path.join(dirname, filename), 'r') as f:
                for l in f:
                    lines += 1
print count, lines

【讨论】:

  • 谢谢。我不确定应该将什么项目放在 os.walk 旁边的括号中。在这里你有'文件夹'。文档有点奇怪,我看到的其他内容也不一致。
  • 谢谢!这真的让我慢了下来。
【解决方案2】:

您可以使用scandir.walk(path) insted of os.walk(path)。与 os.walk() 相比,它可以提供更快的结果。此模块包含在 python35 中,但您可以使用 pip install scandir 来使用 python27、python34。

我的代码在这里:

import os
import scandir

folder = ' ' #here your dir path
print "All files ending with .py in folder %s:" % folder
file_list = []

for paths, dirs, files in scandir.walk(folder):
#for (paths, dirs, files) in os.walk(folder):
    for file in files:
        if file.endswith(".py"):
            file_list.append(os.path.join(paths, file))

print len(file_list),file_list

scandir.walk() 可以在 os.walk() 中做你想做的事。

我希望这个答案与您的问题相匹配,这里是scandir 的文档

【讨论】:

    【解决方案3】:

    在 Python 标准库 3.4 及以上版本中可以使用pathlib

    from pathlib import Path
    
    files = Path().cwd().glob("**/*.ext")
    

    它将返回生成器,其中包含当前和子目录中所有扩展名为“.ext”的文件。然后您可以遍历这些文件

    for f in files:
        print(f)
        # do other stuff
    

    或者你可以一行完成:

    for f in Path().cwd().glob("../*.ext"):
        print(f)
        # do other stuff
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-29
      • 2020-03-29
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      相关资源
      最近更新 更多