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

14 投票
3 回答
16555 浏览
提问于 2025-04-16 14:20

我刚开始学习Python,但已经发现它比Bash脚本要高效得多。

我想写一个Python脚本,这个脚本可以遍历从我启动脚本的目录开始的每一个子目录,并且对于它遇到的每一个文件,加载一个这个类的实例:

class FileInfo:

    def __init__(self, filename, filepath):
        self.filename = filename
        self.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中实现这个功能最简单的方法是什么。提前谢谢你们。

3 个回答

1

试试看

import os

for item in os.walk(".", "*"):
    print(item)
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 实例的列表。

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

撰写回答