目录中的一个完整的文件名,也有共享大部分人的名字两个文件:的Python:获得基于部分文件名
my_file_0_1.txt
my_file_word_0_1.txt
我想开my_file_0_1.txt
我需要以避免指定确切的文件名,而是需要在目录中搜索与部分字符串my_file_0
匹配的文件名。
从this answer here,and 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')'返回一个文件名列表,使用索引来检索你需要的文件。 – vaultah
同意。 'glob.glob'是'fnmatch'的一个包装器,但它是一个包装器,它正是你想要做的事情。 –
@StatsSorceress确保你在运行脚本的目录中有这样的文件,因为'glob'应该可以工作 –