Open a file, knowing only part of its name

I am currently reading a file and importing data into it using the line:

# Read data from file. data = np.loadtxt(join(mypath, 'file.data'), unpack=True) 

where the variable mypath known. The problem is that the file.data file will change over time, assuming names such as:

 file_3453453.data file_12324.data file_987667.data ... 

So, I need to specify the code to open the file in the path that has a name like file*.data , assuming that there will always be only one file with that name in the path. Is there any way to do this in python ?

+4
source share
4 answers

You can use the glob . It allows you to match patterns by file names and does exactly what you ask.

 import glob for fpath in glob.glob(mypath): print fpath 

For example, I have a directory with files named google.xml, google.json and google.csv.

I can use glob as follows:

 >>> import glob >>> glob.glob('g*gle*') ['google.json', 'google.xml', 'google.csv'] 

Note that glob uses the fnmatch module, but has a simpler interface and it maps paths instead of file names.

You can search for relative paths and not use os.path.join . In the above example, if I go to the parent directory and try to match the file names, it returns relative paths:

 >>> import os >>> import glob >>> os.chdir('..') >>> glob.glob('foo/google*') ['foo/google.json', 'foo/google.xml', 'foo/google.csv'] 
+13
source

Also check fnmatch :

 >>> import fnmatch >>> import os >>> >>> fnmatch.filter(os.listdir('.'), 'file_*.data') ['file_3453453.data'] >>> 
+4
source

A simple solution would be to use the python "os" and "re" modules:

 import os import re for file in os.listdir(mypath): if re.match("file_\d+\.data", file): ... 
+2
source

Try

 import os [os.path.join(root, f) for root, _, files in os.walk(mypath) for f in files if f.startswith('file') and f.endswith('.data')] 

It will return a list of all file*.data files if there are more than one. You can just iterate over them. If there is only one file, then just put [0] at the end of the list comprehension.

+1
source

Source: https://habr.com/ru/post/1498865/


All Articles