【问题标题】:Find all files named *.txt in directory [duplicate]在目录中查找所有名为 *.txt 的文件 [重复]
【发布时间】:2018-10-23 05:54:04
【问题描述】:
import os, glob

file = os.listdir("my directory: example")

mp3files = list(filter(lambda f: f == '*.txt',file))    
print(mp3files)

这个代码只给我:[]

【问题讨论】:

  • 提示:使用你正在导入的 glob 模块。 :)
  • 您的lambda f: f == '*.txt' 确实在比较每个文件名以查看它是否与 .txt 匹配,因此它们都失败了,您得到了空列表。 * 仅在某些功能时是通配符,例如正则表达式、字符串、glob 等将其视为通配符。否则它是一个文字 *

标签: python filenames glob


【解决方案1】:
mp3files = list(filter(lambda f: f.endswith('.txt') ,file))

应该可以,因为文件名 (==) 与 *.txt 不匹配,而是以该扩展名结尾

【讨论】:

  • 非常感谢,非常感谢您的帮助
【解决方案2】:

使用str.endswith:

list(filter(lambda f: f.endswith('.txt'),file))

【讨论】:

    【解决方案3】:

    你为什么不使用你已经导入的 glob 模块?

    mp3files = glob.glob('*.txt')
    

    这将返回当前工作目录中所有 mp3 文件的列表。 如果您的文件在不同的目录中而不是在您的 cwd 中:

    path_to_files_dir = os.path.join(os.getcwd(), 'your_files_dir_name', '*.txt')
    
    mp3files = glob.glob(path_to_files)
    

    【讨论】:

    • 很好的解决方案,但他正在寻找 *.txt 文件。
    • 是的,没错,我已将扩展名从 mp3 更改为 txt,谢谢
    • 我知道 glob,但我的任务是使用函数 filter 和 lambda
    【解决方案4】:

    从 Python 3.4 开始,您可以只使用这两行代码来完成该任务:

    from pathlib import Path
    mp3files = list(Path('.').glob('**/*.txt'))
    

    更多信息:https://docs.python.org/3/library/pathlib.html

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 2018-05-14
      • 2018-03-21
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 2014-05-20
      相关资源
      最近更新 更多