问题描述
我目前正在读取文件,并使用以下行将其导入其中:
I'm currently reading a file and importing the data in it with the line:
# Read data from file.
data = np.loadtxt(join(mypath, 'file.data'), unpack=True)
已知变量mypath
的位置.问题是文件file.data
会随着时间的变化而变化,假设名称如下:
where the variable mypath
is known. The issue is that the file file.data
will change with time assuming names like:
file_3453453.data
file_12324.data
file_987667.data
...
因此,我需要一种方法来告诉代码在该路径中打开名称为file*.data
的文件,并假设该路径中始终只有该名称的一个文件. python
有没有办法做到这一点?
So I need a way to tell the code to open the file in that path that has a name like file*.data
, assuming that there will always be only one file by that name in the path. Is there a way to do this in python
?
推荐答案
您可以使用glob
模块.它允许对文件名进行模式匹配,并完全满足您的要求
You can use the glob
module. It allows pattern matching on filenames and does exactly what you're asking
import glob
for fpath in glob.glob(mypath):
print fpath
例如,我有一个目录,其中包含名为google.xml,google.json和google.csv的文件.
e.g I have a directory with files named google.xml, google.json and google.csv.
我可以这样使用glob:
I can use glob like this:
>>> import glob
>>> glob.glob('g*gle*')
['google.json', 'google.xml', 'google.csv']
请注意,glob
使用fnmatch
模块,但是它具有更简单的界面,并且它匹配路径而不是仅匹配文件名.
Note that glob
uses the fnmatch
module but it has a simpler interface and it matches paths instead of filenames only.
您可以搜索相对路径,而不必使用os.path.join
.在上面的示例中,如果我转到父目录并尝试匹配文件名,则它将返回相对路径:
You can search relative paths and don't have to use os.path.join
. In the example above if I change to the parent directory and try to match file names, it returns the relative paths:
>>> import os
>>> import glob
>>> os.chdir('..')
>>> glob.glob('foo/google*')
['foo/google.json', 'foo/google.xml', 'foo/google.csv']
这篇关于打开文件仅知道其名称的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!