Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中迭代多个目录中的文件或整个硬盘驱动器中的文件_Python_Operating System_Glob - Fatal编程技术网

在python中迭代多个目录中的文件或整个硬盘驱动器中的文件

在python中迭代多个目录中的文件或整个硬盘驱动器中的文件,python,operating-system,glob,Python,Operating System,Glob,我有一个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.

我有一个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的信息没有意义


谢谢。

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
您可以使用scandir.walkpath代替os.walkpath。它可以提供比os.walk更快的结果。这个模块包含在python35中,但是您可以使用python27,使用pip安装scandir使用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中执行您想要的操作


我希望这个答案与您的问题相匹配,在这里您可以使用Python标准库3.4及更高版本中的文档

它将返回生成器以及当前和子目录中扩展名为.ext的所有文件。然后可以在这些文件上进行迭代

for f in files:
    print(f)
    # do other stuff
或者,您可以在一行中执行以下操作:

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

发布您的代码,包括您尝试添加“os.walk”的代码,我们可以提供反馈,可能会重复感谢您。我不确定os.walk旁边的括号中应该放什么项目。这里有“文件夹”。文档有点奇怪,我看到的其他东西彼此不一致。谢谢!那真的让我慢了下来。
for f in Path().cwd().glob("../*.ext"):
    print(f)
    # do other stuff