遍历文件

15 投票
5 回答
27926 浏览
提问于 2025-04-18 07:12

我正在尝试把别人的代码改成适合我(Windows 7)使用的版本。可惜他的代码是专门为UNIX系统写的。

dir_ = pathlib.PosixPath(str(somePathVariable))
os.chdir(str(dir_))
for pth in dir_:        
    # some operations here

运行这段代码后,我得到了(这并不意外)

NotImplementedError: cannot instantiate 'PosixPath' on your system

我查了一下pathlib的文档,觉得应该只要把PosixPath改成Path就可以了,结果没问题。可是,dir_却生成了一个WindowsPath对象。到现在为止,一切都还不错。但是,我遇到了

TypeError: 'WindowsPath' object is not iterable

现在pathlib的版本是1.0,我漏掉了什么吗?我的目的是遍历特定目录中的文件。用谷歌搜索这个第二个错误却没有找到任何结果。

备注:无法把pathlib作为标签,所以我把它放在了标题里。

更新

我使用的是Python 2.7.3和pathlib 1.0

5 个回答

0

重要提示:每当你遇到 object is not iterable 的错误时,记住系统也会对字符串进行迭代。举个例子:

import yagmail

def send_email(to: list, subject: str, content: list, attachments=None):
    yagmail.SMTP(from_user_name, password)\
    .send(to=to, subject=subject, contents=content, attachments=attachments)

这个函数的内容也包括电子邮件的内容,附件必须放在列表里!即使只有一个文件也要这样做。

总结:总是尝试把字符串放进列表里,这样可以避免很多问题。

1
dir_ = pathlib.Path(str(somePathVariable))
os.chdir(str(dir_))
for pth in dir_:        
    # some operations here

现在你的代码可以在两个平台上都运行了。你需要指定路径的类型……如果想让它在不同平台上都能用,就得用“Path”,而不是“PosixPath”。

1

可以使用 glob 模块,它在两个平台上都能正常工作:

import glob
for item in glob.glob('/your/path/*')  # use any mask suitable for you
   print item # prints full file path
3

试试这个

for pth in dir_.iterdir():

相关文档可以在这里找到: https://docs.python.org/3/library/pathlib.html#pathlib.Path.iterdir

29

我觉得你应该使用 Path.iterdir() 这个方法。

for pth in dir_.iterdir():

    #Do your stuff here

撰写回答