Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法使用字典从文件列表打印文件名_Python_Dictionary - Fatal编程技术网

Python 无法使用字典从文件列表打印文件名

Python 无法使用字典从文件列表打印文件名,python,dictionary,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

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

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()
这是我的密码。我在这里面临两个问题

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

  • 为什么这个代码是错误的?提前感谢

    您从函数参数中获取了错误的参数,应该从
    else
    语句中删除
    return

    正确的代码为:

    导入操作系统
    def文件():
    files=os.listdir()
    文件\u找到\u标志=False
    对于文件中的文件:
    如果file.lower().endswith('.jpg'):
    name=Dict['jpg']
    名称(文件)
    文件\u找到\u标志=真
    elif file.lower().endswith('.pdf'):
    e=Dict['pdf']
    e(文件)
    文件\u找到\u标志=真
    elif file.lower().endswith('.xlsx'):
    f=Dict['xlsx']
    f(文件)
    文件\u找到\u标志=真
    如果未找到文件\u\u标志:
    打印('未找到文件')
    def jpg(文件):
    打印('找到图像文件{}'。格式(文件))
    def pdf(文件):
    打印('pdf文件找到{}'。格式(文件))
    def xlsx(文件):
    打印('找到excel文件{}'。格式(文件))
    Dict={“jpg”:jpg,“pdf”:pdf,“xlsx”:xlsx}
    文件()
    
    你可以像这样干净利落地做

    EXT_IMAGES = ['.png', '.jpg', '.jpeg', '.bmp', '.svg']
    EXT_VIDEOS = ['.mp4', '.mkv', '.webm', '.mpeg', '.flv', '.m4a', '.f4v', '.f4a', '.m4b', '.m4r', '.f4b', '.mov', '.avi', '.wmv']
    EXT_AUDIOS = ['.mp3', '.wav', '.raw', '.wma']
    EXT_EXCEL = ['.xlsx']
    
    def check_files():
        files = os.listdir()
        for file in files:
            filename, extension = os.path.splitext(file)
            if extension in EXT_IMAGES:
                print('image file found {}'.format(file))
            elif extension in EXT_VIDEOS:
                print('video file found {}'.format(file))
            elif extension in EXT_AUDIOS:
                print('audio file found {}'.format(file))
            elif extension in EXT_EXCEL:
                print('excel file found {}'.format(file))
            else:
                print('unknown file found: %s' % file)
    
    check_files()
    

    我注意到您的代码中可能存在一些错误:

  • 文件是Python中的内置文件。您可能希望将变量名更改为文件以外的名称

    for f in files:
        if f.lower().endswith('.jpg'):
            name= Dict['jpg']
            name(f)
        elif f.lower().endswith('.pdf'):
            e= Dict['pdf']
            e(f)
        elif f.lower().endswith('.xlsx'):
            func= Dict['xlsx']
            func(f)
        else:
            print('no file found')
            return
    
  • 您在jpeg、xlsx和pdf方法中使用的参数不正确

    def jpg(d): 打印('找到图像文件{}'。格式(d))

  • 在我的案例中产生的输出:

    image file found abc.Jpg
    image file found ferf.jpg
    pdf file found vber.pdf
    excel file found uvier.xlsx
    

    返回
    立即中断该功能。第一个文件有
    .Jpeg
    扩展名(大写J),您还没有说明,因此循环中的
    else
    条件为
    True
    ,您从
    文件中分离出来
    我怀疑函数字典比简单的
    打印
    更重要,这个功能在你的方法中丢失了。从我的观点来看,如果他使用了
    Dict
    和数据样本进行测试,不管怎么说,这看起来都是多余的。他仍然可以从if块调用他的函数。又不是什么东西坏了!我没说它坏了。看起来他们想要的是分派方法
    文件
    不是Python 3中内置的,您真的不应该使用Python 2,它将失去未来的支持。我认为这是正确的答案。它解决了查看
    未找到文件
    错误的主要问题。此外,我建议在扩展分支中添加一个
    else
    子句。使用
    logging.debug()
    或类似工具。这将使您更容易发现目前没有提示的意外错误。非常感谢。成功了。现在我明白出了什么问题。非常感谢。