Python程序遍历目录并读取文件信息
问题描述:
我刚刚开始使用Python,但已经发现它比Bash shell脚本更有效率。Python程序遍历目录并读取文件信息
我想写一个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中实现这个最直接的方法是什么。提前致谢。
答
我会使用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
+0
使用snake_case代替Python的CamelCase。 – franka 2014-04-21 12:43:42
答
尝试
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
的列表。
答
试试吧
进口OS
在os.walk(项目” *“):
print item
你想在哪里分配创建的对象?这似乎是微不足道的。 – Ofir 2011-03-24 15:35:30