Skip to main content
 首页 » 编程设计

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

2025年02月15日10softidea

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

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?":