gpt4 book ai didi

python-3.x - fnmatch 不显示所有匹配的文件名

转载 作者:行者123 更新时间:2023-12-01 22:04:46 26 4
gpt4 key购买 nike

我有一个包含 5 个文件的文件夹,分别命名为 'out1.jpg'、'out2a.jpg'、'out2b.jpg' , 'out3.jpg' 和 'out4.jpg' 以及其他不同格式的文件。我有这个 Python 脚本,它应该打印所有匹配的文件名:

import fnmatch
import os

c = 1
for file in os.listdir('.'):
if fnmatch.fnmatch(file, 'out'+str(c)+'*.jpg'):
print(file)
c +=1

但是,当我运行这个脚本时,输出仅限于以下内容:

out1.jpg
out2a.jpg
out3.jpg

有人知道如何更改脚本以显示所有匹配的文件名(我提到的 5 个文件名)吗?

最佳答案

您在每次迭代中都增加了 c(好吧,在每次找到匹配项的迭代中,但无论如何......),因此它显然不能匹配“out2a.jpg”和“out2b.jpg” .假设您想要所有匹配“out”的文件名+一些数字+最终是其他东西,您可以改用字符范围;即:

for file in os.listdir('.'):
if fnmatch.fnmatch(file, 'out[0-9]*.jpg'):
print(file)

注意:您可能需要根据您的需要和目录中的内容调整确切的 fnmatch 模式。

您也可以改用 glob.glob,这既更简单又(根据文档)更高效:

import glob
for file in glob("out[0-9]*.jpg"):
print(file)

编辑:

I totally understand why it does not display out2a.jpg and out2b.jpg together, but I didn't get why out4.jpg is not displayed!

很简单,因为 os.listdir() 不一定按照您预期的顺序返回文件名(在我的 linux 站上,“out4.jpg”出现在另一个之前“outXXX.jpg”文件)。您可以通过添加几个打印件来检查发生了什么:

c = 1
for file in os.listdir('.'):
exp = 'out{}*.jpg'.format(c)
print("file: {} - c : {} - exp : {}".format(file, c, exp))
if fnmatch.fnmatch(file, exp):
print(file)
c +=1

结果在这里:

file: sofnm.py~ - c : 1 - exp : out1*.jpg
file: out4.jpg - c : 1 - exp : out1*.jpg
file: out2b.jpg - c : 1 - exp : out1*.jpg
file: out1.jpg - c : 1 - exp : out1*.jpg
out1.jpg
file: out2a.jpg - c : 2 - exp : out2*.jpg
out2a.jpg
file: sofnm.py - c : 3 - exp : out3*.jpg
file: out42a.jpg - c : 3 - exp : out3*.jpg
file: out3.jpg - c : 3 - exp : out3*.jpg
out3.jpg

如您所见,您关于 os.listdir() 将按给定顺序返回文件(从“out1.jpg”开始到“out4.jpg”结束)的假设是错误的.作为一般规则,当您的代码未按预期运行时,跟踪代码执行(和相关值)通常是找出原因的最简单方法。

关于python-3.x - fnmatch 不显示所有匹配的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52495600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com