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 中实现这个将会是。提前致谢。
I'm just getting started with Python but already have found it much more productive than Bash shell scripting.
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
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用 os.walk 执行以下操作:
I'd use
os.walk
doing the following:尝试
或
获取每个文件一个
FileInfo
实例的列表。Try
or
to get a list of one
FileInfo
instance per file.尝试一下
Try it