Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file knowing only a part of its name

Tags:

python

naming

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)

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
...

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?

like image 648
Gabriel Avatar asked Aug 25 '13 20:08

Gabriel


People also ask

How do I search for a file with a specific name in Python?

Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.

What are the parts of file name?

Windows file names have two parts; the file's name, then a period followed by the extension (suffix).

Which parameter is used to open a file for reading only?

Take note that only the filename parameter was specified, this is due to the "read" mode being the default mode for the open function. The access modes available for the open() function are as follows: r : Opens the file in read-only mode.

How do we search for all the files whose name start from test in the home directory?

Finding Files with bat Anywhere To search your whole computer, use / . To search your home directory, use ~ , or the full name of your home directory. (The shell expands ~ to your home directory's fully qualified path.)


1 Answers

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

e.g I have a directory with files named google.xml, google.json and google.csv.

I can use glob like this:

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

Note that glob uses the fnmatch module but it has a simpler interface and it matches paths instead of filenames only.

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']
like image 88
MrD Avatar answered Sep 29 '22 23:09

MrD