python - 如何打印文件夹中具有特定名称的文件

标签 python string loops

我有一个文件夹,其中包含许多名称相似的文件。到目前为止,这是我的代码。

directory = r"C:\Users\matth\Downloads\AMSRE"
for root, dirs, filenames in os.walk(directory):
    for f in filenames:           
        if f == "AMSR_E_L3_DailyLand_V06_201001?":
            log = open(os.path.join(root, f), 'r')
            file_name = (("C:\\Users\\matth\\Downloads\\AMSRE\\") + f)
            print(file_name)

但是,没有打印任何内容。我使用了这一行 if f == "AMSR_E_L3_DailyLand_V06_201001?": 因为我有很多名称相似的文件:

  • AMSR_E_L3_DailyLand_V06_20100101.hdf,
  • AMSR_E_L3_DailyLand_V06_20100102.hdf,
  • AMSR_E_L3_DailyLand_V06_20100103.hdf,
  • 等等。

我不确定我是否正确使用了问号。有谁知道出了什么问题吗?

最佳答案

Python 在正常比较中不支持通配符或占位符,如 *?。正如 @inspectorG4dget 在评论中指出的那样,您可以只检查它是否以特定字符串 ( str.startswith) 开头:

if f.startswith("AMSR_E_L3_DailyLand_V06_201001"):

代替:

if f == "AMSR_E_L3_DailyLand_V06_201001?":

关于python - 如何打印文件夹中具有特定名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45467539/

相关文章:

JAVA - 在数组中存储 Int 和 Float 而不是其他数据类型

loops - 循环文件时数组元素被删除

python - 如何在 Python 中使用 Windows 文件路径 __doc__

Python GC 计数器 - Rosalind

Python CTRL-C 退出没有回溯?

c - 字符串减去C中的字符串

c - 如何在C语言中查找文本文件中的字符串?

excel - VBA Excel 比较两个列表是否匹配,在单独的工作表上输出结果

Python execv 和管道输出

java - 在 Java 中替换字符串的首字母?