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

2024-04-26 07:36:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始使用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中实现这一点最简单的方法是什么。提前谢谢。


Tags: andofpathself目录脚本bashshell
3条回答

我将使用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

试试看

import os

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

     print item 

试试看

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实例的列表。

相关问题 更多 >