ChatGPT解决这个技术问题 Extra ChatGPT

Python递归文件夹读取

我有 C++/Obj-C 背景,我刚刚发现 Python(已经写了大约一个小时)。我正在编写一个脚本来递归读取文件夹结构中文本文件的内容。

我遇到的问题是我编写的代码仅适用于一个文件夹深处。我可以在代码中看到为什么(参见 #hardcoded path),我只是不知道如何继续使用 Python,因为我对它的体验是全新的。

蟒蛇代码:

import os
import sys

rootdir = sys.argv[1]

for root, subFolders, files in os.walk(rootdir):

    for folder in subFolders:
        outfileName = rootdir + "/" + folder + "/py-outfile.txt" # hardcoded path
        folderOut = open( outfileName, 'w' )
        print "outfileName is " + outfileName

        for file in files:
            filePath = rootdir + '/' + file
            f = open( filePath, 'r' )
            toWrite = f.read()
            print "Writing '" + toWrite + "' to" + filePath
            folderOut.write( toWrite )
            f.close()

        folderOut.close()

A
AndiDog

确保您了解 os.walk 的三个返回值:

for root, subdirs, files in os.walk(rootdir):

具有以下含义:

根:“走过”的当前路径

subdirs:目录类型根目录中的文件

文件:根目录(不在子目录中)的文件类型,而不是目录

请使用 os.path.join 而不是用斜杠连接!您的问题是 filePath = rootdir + '/' + file - 您必须连接当前的“walked”文件夹而不是最顶层的文件夹。所以那一定是filePath = os.path.join(root, file)。顺便说一句,“文件”是内置的,因此您通常不会将其用作变量名。

另一个问题是你的循环,应该是这样的,例如:

import os
import sys

walk_dir = sys.argv[1]

print('walk_dir = ' + walk_dir)

# If your current working directory may change during script execution, it's recommended to
# immediately convert program arguments to an absolute path. Then the variable root below will
# be an absolute path as well. Example:
# walk_dir = os.path.abspath(walk_dir)
print('walk_dir (absolute) = ' + os.path.abspath(walk_dir))

for root, subdirs, files in os.walk(walk_dir):
    print('--\nroot = ' + root)
    list_file_path = os.path.join(root, 'my-directory-list.txt')
    print('list_file_path = ' + list_file_path)

    with open(list_file_path, 'wb') as list_file:
        for subdir in subdirs:
            print('\t- subdirectory ' + subdir)

        for filename in files:
            file_path = os.path.join(root, filename)

            print('\t- file %s (full path: %s)' % (filename, file_path))

            with open(file_path, 'rb') as f:
                f_content = f.read()
                list_file.write(('The file %s contains:\n' % filename).encode('utf-8'))
                list_file.write(f_content)
                list_file.write(b'\n')

如果您不知道,文件的 with 语句是简写:

with open('filename', 'rb') as f:
    dosomething()

# is effectively the same as

f = open('filename', 'rb')
try:
    dosomething()
finally:
    f.close()

精湛的,大量的印刷品来了解发生了什么,它完美地工作。谢谢! +1
向像我一样愚蠢/健忘的人注意……此代码示例将一个 txt 文件写入每个目录。很高兴我在版本控制的文件夹中对其进行了测试,尽管我需要编写清理脚本的所有内容都在这里 :)
第二个(最长的)代码片段运行良好,为我省去了很多无聊的工作
由于速度显然是最重要的方面,os.walk 还不错,尽管我通过 os.scandir 想出了一个更快的方法。所有 glob 解决方案都比 walk & scandir。我的函数以及完整的速度分析可以在这里找到:stackoverflow.com/a/59803793/2441026
A
AnaS Kayed

如果您使用的是 Python 3.5 或更高版本,则可以在 1 行中完成此操作。

import glob

# root_dir needs a trailing slash (i.e. /root/dir/)
for filename in glob.iglob(root_dir + '**/*.txt', recursive=True):
     print(filename)

documentation 中所述

如果 recursive 为真,则模式 '**' 将匹配任何文件以及零个或多个目录和子目录。

如果你想要每个文件,你可以使用

import glob

for filename in glob.iglob(root_dir + '**/**', recursive=True):
     print(filename)

如开头所述,仅适用于 Python 3.5+
root_dir 必须有一个斜杠(否则你会得到类似 'folder**/*' 而不是 'folder/**/*' 作为第一个参数)。您可以使用 os.path.join(root_dir, '*/'),但我不知道是否可以将 os.path.join 与通配符路径一起使用(尽管它适用于我的应用程序)。
@ChillarAnand 您能否在此答案中的代码中添加注释,root_dir 需要尾部斜杠?这将节省人们的时间(或者至少它会节省我的时间)。谢谢。
如果我按照答案运行它,它就不能递归地工作。为了递归地进行这项工作,我必须将其更改为:glob.iglob(root_dir + '**/**', recursive=True)。我正在使用 Python 3.8.2
请注意 glob.glob 与点文件不匹配。您可以改用 pathlib.glob
t
the Tin Man

同意 Dave Webb,os.walk 将为树中的每个目录生成一个项目。事实上,您不必关心 subFolders

像这样的代码应该可以工作:

import os
import sys

rootdir = sys.argv[1]

for folder, subs, files in os.walk(rootdir):
    with open(os.path.join(folder, 'python-outfile.txt'), 'w') as dest:
        for filename in files:
            with open(os.path.join(folder, filename), 'r') as src:
                dest.write(src.read())

好东西。这也有效。然而,我确实更喜欢 AndiDog 的版本,尽管它更长,因为作为 Python 的初学者更容易理解。 +1
L
Luc

TL;DR: 这相当于 find -type f 遍历以下所有文件夹中的所有文件,包括当前文件夹:

for currentpath, folders, files in os.walk('.'):
    for file in files:
        print(os.path.join(currentpath, file))

正如其他答案中已经提到的,os.walk() 是答案,但可以更好地解释。这很简单!让我们走过这棵树:

docs/
└── doc1.odt
pics/
todo.txt

使用此代码:

for currentpath, folders, files in os.walk('.'):
    print(currentpath)

currentpath 是它正在查看的当前文件夹。这将输出:

.
./docs
./pics

所以它循环了 3 次,因为有 3 个文件夹:当前文件夹、docspics。在每个循环中,它用所有文件夹和文件填充变量 foldersfiles。让我们向他们展示:

for currentpath, folders, files in os.walk('.'):
    print(currentpath, folders, files)

这向我们展示了:

# currentpath  folders           files
.              ['pics', 'docs']  ['todo.txt']
./pics         []                []
./docs         []                ['doc1.odt']

因此,在第一行中,我们看到我们在文件夹 . 中,它包含两个文件夹,即 picsdocs,并且有一个文件,即 todo.txt。您无需执行任何操作即可递归到这些文件夹中,因为如您所见,它会自动递归并为您提供任何子文件夹中的文件。以及它的任何子文件夹(尽管我们在示例中没有这些子文件夹)。

如果您只想遍历所有文件,相当于 find -type f,您可以这样做:

for currentpath, folders, files in os.walk('.'):
    for file in files:
        print(os.path.join(currentpath, file))

这输出:

./todo.txt
./docs/doc1.odt

d
dstandish

pathlib 库非常适合处理文件。您可以像这样对 Path 对象执行递归 glob。

from pathlib import Path

for elem in Path('/path/to/my/files').rglob('*.*'):
    print(elem)

N
Neeraj Sonaniya
import glob
import os

root_dir = <root_dir_here>

for filename in glob.iglob(root_dir + '**/**', recursive=True):
    if os.path.isfile(filename):
        with open(filename,'r') as file:
            print(file.read())

**/** 用于递归获取所有文件,包括 directory

if os.path.isfile(filename) 用于检查 filename 变量是 file 还是 directory,如果是文件,那么我们可以读取该文件。我在这里打印文件。


S
Scott Smith

如果您想要一个给定目录下所有路径的平面列表(如 shell 中的 find .):

   files = [ 
       os.path.join(parent, name)
       for (parent, subdirs, files) in os.walk(YOUR_DIRECTORY)
       for name in files + subdirs
   ]

要仅包含基本目录下文件的完整路径,请省略 + subdirs


M
Michael Silverstein

我发现以下是最简单的

from glob import glob
import os

files = [f for f in glob('rootdir/**', recursive=True) if os.path.isfile(f)]

使用 glob('some/path/**', recursive=True) 获取所有文件,但也包括目录名称。添加 if os.path.isfile(f) 条件仅将此列表过滤到现有文件


t
the Tin Man

使用 os.path.join() 构建路径 - 更简洁:

import os
import sys
rootdir = sys.argv[1]
for root, subFolders, files in os.walk(rootdir):
    for folder in subFolders:
        outfileName = os.path.join(root,folder,"py-outfile.txt")
        folderOut = open( outfileName, 'w' )
        print "outfileName is " + outfileName
        for file in files:
            filePath = os.path.join(root,file)
            toWrite = open( filePath).read()
            print "Writing '" + toWrite + "' to" + filePath
            folderOut.write( toWrite )
        folderOut.close()

看起来此代码仅适用于 2 级(或更深)的文件夹。它仍然让我更接近。
G
Gwang-Jin Kim

在我看来,os.walk() 有点过于复杂和冗长。您可以通过以下方式使接受的答案更清洁:

all_files = [str(f) for f in pathlib.Path(dir_path).glob("**/*") if f.is_file()]

with open(outfile, 'wb') as fout:
    for f in all_files:
        with open(f, 'rb') as fin:
            fout.write(fin.read())
            fout.write(b'\n')

t
the Tin Man

os.walk 默认执行递归遍历。对于每个目录,从根目录开始,它会产生一个 3 元组(目录路径、目录名、文件名)

from os import walk
from os.path import splitext, join

def select_files(root, files):
    """
    simple logic here to filter out interesting files
    .py files in this example
    """

    selected_files = []

    for file in files:
        #do concatenation here to get full path 
        full_path = join(root, file)
        ext = splitext(file)[1]

        if ext == ".py":
            selected_files.append(full_path)

    return selected_files

def build_recursive_dir_tree(path):
    """
    path    -    where to begin folder scan
    """
    selected_files = []

    for root, dirs, files in walk(path):
        selected_files += select_files(root, files)

    return selected_files

在 Python 2.6 walk() do 返回递归列表。我尝试了您的代码并获得了一个包含许多重复项的列表...如果您只是删除注释“# recursive calls on subfolders”下的行-它可以正常工作
t
the Tin Man

我认为问题在于您没有正确处理 os.walk 的输出。

首先,改变:

filePath = rootdir + '/' + file

至:

filePath = root + '/' + file

rootdir 是您的固定起始目录; rootos.walk 返回的目录。

其次,您不需要缩进文件处理循环,因为为每个子目录运行它是没有意义的。您将 root 设置为每个子目录。除非您想对目录本身做些什么,否则您不需要手动处理子目录。


我在每个子目录中都有数据,因此我需要为每个目录的内容创建一个单独的文本文件。
@Brock:文件部分是当前目录中的文件列表。所以缩进确实是错误的。您正在写入 filePath = rootdir + '/' + file,这听起来不对:文件来自当前文件列表,所以您正在写入很多现有文件?
D
Diego

尝试这个:

import os
import sys

for root, subdirs, files in os.walk(path):

    for file in os.listdir(root):

        filePath = os.path.join(root, file)

        if os.path.isdir(filePath):
            pass

        else:
            f = open (filePath, 'r')
            # Do Stuff

当您已经将目录列表从 walk() 拆分为文件和目录时,为什么还要执行另一个 listdir() 和 isdir()?这看起来在大型树中会相当慢(执行三个系统调用而不是一个:1=walk、2=listdir、3=isdir,而不是仅仅遍历“subdirs”和“files”)。
k
knall0

如果您更喜欢(几乎)Oneliner:

from pathlib import Path

lookuppath = '.' #use your path
filelist = [str(item) for item in Path(lookuppath).glob("**/*") if Path(item).is_file()]

在这种情况下,您将获得一个列表,其中仅包含递归位于查找路径下的所有文件的路径。如果没有 str(),您将在每个路径中添加 PosixPath()。


n
neuviemeporte

如果仅文件名还不够,在 os.scandir() 之上实现 Depth-first search 很容易:

stack = ['.']
files = []
total_size = 0
while stack:
    dirname = stack.pop()
    with os.scandir(dirname) as it:
        for e in it:
            if e.is_dir(): 
                stack.append(e.path)
            else:
                size = e.stat().st_size
                files.append((e.path, size))
                total_size += size

docs 有这样的说法:

scandir() 函数返回目录条目以及文件属性信息,为许多常见用例提供更好的性能。


S
Scott

这对我有用:

import glob

root_dir = "C:\\Users\\Scott\\" # Don't forget trailing (last) slashes    
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
     print(filename)
     # do stuff