2017-07-30 54 views
1

目录中的一个完整的文件名,也有共享大部分人的名字两个文件:的Python:获得基于部分文件名

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

如何根据字符串匹配的结果找到并存储文件的名称?

+2

'glob.glob'是我要走的路,我想。 'glob.glob('my_file_0 * .txt')'返回一个文件名列表,使用索引来检索你需要的文件。 – vaultah

+0

同意。 'glob.glob'是'fnmatch'的一个包装器,但它是一个包装器,它正是你想要做的事情。 –

+0

@StatsSorceress确保你在运行脚本的目录中有这样的文件,因为'glob'应该可以工作 –

回答

2

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 
0

一个解决方案使用os.listdir()

不是也可能你使用os模块搜索os.listdir()?例如:

import os 

partialFileName = "my_file_0" 

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