【问题标题】:In a for loop, how can I assign the variable to a specific file-type? [duplicate]在 for 循环中,如何将变量分配给特定的文件类型? [复制]
【发布时间】:2020-10-30 10:27:50
【问题描述】:

我在 python 中使用os.walk 命令来浏览目录的所有内容。我正在对目录中所有文件夹和子文件夹中的文件运行辅助 for 循环。弹出一个错误,说它不知道如何处理存在的.txt 文件(我的代码特定于.png 文件)。我希望辅助 for 循环仅在 .png 文件类型上运行,并忽略 .txt 或带有 .png 图像的文件夹中的其他文件。我尝试了assert 命令,但无法正常工作。如何将其限制为 .png 文件?

for root, dirs, files in os.walk(r"/mnt/c/Users/james/Documents/ListingTest/", topdown=True):
    for image in files:
        assert image is filetype: .png
        print(os.path.join(root, image))
        

我无法正确获取断言函数语法,甚至不知道它是否是我需要使用的命令。

【问题讨论】:

  • assert image.endswith('.png')?实际上并没有验证它实际上是一个 PNG 文件(如果你想确定,你需要解析每个文件),但这是简单的文件扩展测试。请参阅下面 chepner 的评论,了解 assert 如何不是您真正想要的。您想要if not image.endswith('.png'): continue 或翻转测试并将操作放在if 的正文中。
  • assert 旨在终止您的程序;它不会简单地跳过循环的这个迭代。

标签: python for-loop nested assert os.walk


【解决方案1】:

试试:

for image in files:
    if image.lower().endswith(".png"):
        print(os.path.join(root, image))

这将打印所有以.png 结尾的文件路径。如 cmets 中所述,这实际上并不能保证文件是图像。任何带有上述扩展名的文件都会被打印出来。

【讨论】:

  • 这成功了!非常感谢
猜你喜欢
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
  • 2018-07-11
  • 2012-04-26
  • 1970-01-01
  • 2021-02-23
  • 2015-07-07
相关资源
最近更新 更多