gpt4 book ai didi

python - 无法使用字典从文件列表中打印文件名

转载 作者:行者123 更新时间:2023-12-01 00:22:05 24 4
gpt4 key购买 nike

我有一个目录中的文件列表。我想遍历文件名并在找到特定文件扩展名时调用函数

def files():
files = os.listdir()
# files = ['abc.Jpg','ferf.jpg','vber.pdf','uvier.xlsx']

for file in files:
if file.lower().endswith('.jpg'):
name= Dict['jpg']
name(file)
elif file.lower().endswith('.pdf'):
e= Dict['pdf']
e(file)
elif file.lower().endswith('.xlsx'):
f= Dict['xlsx']
f(file)
else:
print('no file found')
return

def jpg(d):
print('image file found {}'.format(file))

def pdf(e):
print('pdf file found {}'.format(file))

def xlsx(f):
print('excel file found {}'.format(file))


Dict={"jpg":jpg, "pdf":pdf,"xlsx":xlsx }
files()

这是我的代码。我在这里面临两个问题。

  1. 如果我从目录中选择文件,它不会迭代并给出输出“找不到文件”
  2. 如果我手动输入列表而不是打印单独的文件名,则只会重复打印第一个文件名

这段代码为什么错了?提前致谢

最佳答案

您从函数参数中获取了错误的参数,应从 else 语句中删除 return:
正确的代码是:

import os

def files():
files = os.listdir()

file_found_flag = False
for file in files:
if file.lower().endswith('.jpg'):
name= Dict['jpg']
name(file)
file_found_flag = True
elif file.lower().endswith('.pdf'):
e= Dict['pdf']
e(file)
file_found_flag = True

elif file.lower().endswith('.xlsx'):
f= Dict['xlsx']
f(file)
file_found_flag = True

if not file_found_flag:
print('no file found')


def jpg(file):
print('image file found {}'.format(file))

def pdf(file):
print('pdf file found {}'.format(file))

def xlsx(file):
print('excel file found {}'.format(file))


Dict={"jpg":jpg, "pdf":pdf,"xlsx":xlsx }
files()

关于python - 无法使用字典从文件列表中打印文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58889234/

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