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

标签 python dictionary

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

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/

相关文章:

python - 如何在Python中使用concat将数据帧的每一行转换为新列

javascript - Python 将 JavascriptSerializer 转换为日期时间?

python - 有没有办法更新Python字典的值,但如果键不存在则不添加键?

java - 将字符串解析为映射的最有效方法是什么?

Python - 迭代字典匹配

python - 如何在 Python 中使用 __slots__ 获取类中的实例属性名称值

Python 数据库错误

Python将字符串附加到列表而不提及列表

python - 将数组/列表转换为字典的有效方法是什么?

python - 如何将字典与相同的键结合起来?