Python程序遍历目录并读取文件信息 [英] Python program to traverse directories and read file information

查看:372
本文介绍了Python程序遍历目录并读取文件信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Python,但是已经发现它比Bash Shell脚本更具生产力.

I'm just getting started with Python but already have found it much more productive than Bash shell scripting.

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

I'm trying to write a Python script that will traverse every directory that branches from the directory I launch the script in, and for each file it encounters, load an instance of this class:

class FileInfo:

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

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

The filepath attribute would be the full absolute path from root (/). Here's the pseudocode mockup for what I'd like the main program to do:

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中实现此最直接方法的建议.预先感谢.

I've been reading about os.walk() and ok.path.walk(), but I'd like some advice about what the most straightforward way to implement this in Python would be. Thanks in advance.

推荐答案

我将使用os.walk进行以下操作:

I'd use os.walk doing the following:

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

这篇关于Python程序遍历目录并读取文件信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆