【问题标题】:Python: get a complete file name based on a partial file namePython:根据部分文件名获取完整的文件名
【发布时间】:2017-07-30 20:43:20
【问题描述】:

在一个目录中,有两个文件大部分名称相同:

my_file_0_1.txt
my_file_word_0_1.txt

我想打开my_file_0_1.txt

我需要避免指定确切的文件名,而是需要在目录中搜索与部分字符串 my_file_0 匹配的文件名。

来自this answer hereand this one,我尝试了以下:

import numpy as np
import os, fnmatch, glob

def find(pattern, path):
        result = []
        for root, dirs, files in os.walk(path):
                for name in files:
                        if fnmatch.fnmatch(name, pattern):
                                result.append(os.path.join(root, name))
        return result

if __name__=='__main__':

        #filename=find('my_file_0*.txt', '/path/to/file')
        #print filename
        print glob.glob('my_file_0' + '*' + '.txt')

这些都不会打印实际的文件名,供我稍后使用np.loadtxt 阅读。

如何根据字符串匹配的结果查找和存储文件名?

【问题讨论】:

  • glob.glob 是要走的路,我想。 glob.glob('my_file_0*.txt')返回文件名列表,使用索引检索你需要的文件。
  • 同意。 glob.globfnmatch 的包装器,但它是一个包装器,它完全可以在此处完成您想做的事情。
  • @StatsSorceress 确保您在运行脚本的目录中有此文件,因为glob 应该可以工作

标签: python


【解决方案1】:

glob.glob() 需要一个有效的路径,如果您在另一个目录中运行脚本,它将找不到您期望的内容。 (可以用os.getcwd()查看当前目录)

它应该与下面的行一起使用:

print glob.glob('path/to/search/my_file_0' + '*.txt')

print glob.glob(r'C:\path\to\search\my_file_0' + '*.txt') # for windows

【讨论】:

    【解决方案2】:

    使用os.listdir()的解决方案

    你不能也使用os 模块来搜索os.listdir() 吗?比如:

    import os
    
    partialFileName = "my_file_0"
    
    for f in os.listdir():
        if partialFileName = f[:len(partialFileName)]:
            print(f)
    

    【讨论】:

      【解决方案3】:

      我刚刚开发了以下方法,并正在搜索是否有更好的方法并遇到了您的问题。我想你可能会喜欢这种方法。我需要与您要求的几乎相同的东西,并使用列表理解提出了这个干净的衬里,并且肯定期望只有一个文件名符合我的标准。我修改了我的代码以匹配您的问题。

      import os
      
      
      file_name = [n for n in os.listdir("C:/Your/Path") if 'my_file_0' in n][0]
      print(file)
      

      现在,如果这是循环/重复调用的情况,您可以修改如下:

      for i in range(1, 4):
          file = [n for n in os.listdir("C:/Your/Path") if f'my_file_{i}' in n][0]
          print(file)
      

      或者,可能更实际...

      def get_file_name_with_number(num):
          file = [n for n in os.listdir("C:/Your/Path") if f'my_file_{num}' in n][0]
          return file
      
      
      print(get_file_name_with_number(0))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-12
        • 2022-12-01
        • 2018-11-16
        • 1970-01-01
        • 1970-01-01
        • 2011-04-13
        • 1970-01-01
        相关资源
        最近更新 更多