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

时间:2011-03-24 15:30:58

标签: python fileinfo directory-traversal

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

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

class FileInfo:

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

filepath属性是root(/)的完整绝对路径。这是我想要主程序要做的伪代码模型:

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 个答案:

答案 0 :(得分: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 :(得分: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个实例的列表。

答案 2 :(得分:1)

试试吧

  
    
      

导入os

             

表示os.walk中的项目(“。”,“*”):

    
  
     print item 
相关问题