Python程序遍历目录并读取文件信息

14

我刚开始接触Python,但已经发现它比Bash shell脚本更有效率了。

我正在尝试编写一个Python脚本,它将遍历从我启动脚本的目录分支出的每个目录,并对遇到的每个文件加载此类的实例:

class FileInfo:

    def __init__(self, filename, filepath):
        self.filename = filename
        self.filepath = filepath

filepath 属性将是从根目录 (/) 开始的完整绝对路径。这是我想要主程序执行的伪代码模型:

from (current directory):

    for each file in this directory, 
    create an instance of FileInfo and load the file name and path

    switch to a nested directory, or if there is none, back out of this directory

我一直在阅读有关os.walk()和ok.path.walk()的内容,但我想知道在Python中实现这个功能最简单的方法是什么。谢谢。


你想把创建的对象分配到哪里?这似乎是非常简单的。 - Ofir
3个回答

17

我会使用os.walk来完成以下操作:

def getInfos(currentDir):
    infos = []
    for root, dirs, files in os.walk(currentDir): # Walk directory tree
        for f in files:
            infos.append(FileInfo(f,root))
    return infos

1
使用snake_case而不是CamelCase来编写Python代码。 - franka

7

尝试

info = []
for path, dirs, files in os.walk("."):
    info.extend(FileInfo(filename, path) for filename in files)

或者

info = [FileInfo(filename, path)
        for path, dirs, files in os.walk(".")
        for filename in files]

获取每个文件一个FileInfo实例的列表。


1
尝试一下。
import os

for item in os.walk(".", "*"):
    print(item)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接