You are on page 1of 2

linux - Search a folder for files like "/*tmp*.log" in Python - Stack Ove...

1 of 2

http://stackoverflow.com/questions/1090651/search-a-folder-for-files-l...

sign up

log in

tour

help

stack overflow careers

Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

Search a folder for files like /*tmp*.log in Python


As the title says, I'm using Linux, and the folder could contain more than one file, I want to get the one its name contain
means anything of course!). Just like what I do using Linux command line.
python

linux

file

*tmp*.log

folders

edited Jul 7 '09 at 6:25

asked Jul 7 '09 at 6:17

Miles
15.9k

JustRegisterMe
3

41

66

752

3 Answers

Use the

glob

module.

>>> import glob


>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']

answered Jul 7 '09 at 6:18


Otto Allmendinger
14.2k

44

67

Worked like a charm, thanks for this very fast answer! JustRegisterMe Jul 7 '09 at 6:26

The glob answer is easier, but for the sake of completeness: You could also use os.listdir and
a regular expression check:
import os
import re
dirEntries = os.listdir(path/to/dir)
for entry in dirEntries:
if re.match(".*tmp.*\.log", entry):
print entry

answered Jul 7 '09 at 18:43


PTBNL
2,927

19

25

don't even have to use re. ghostdog74 Jul 9 '09 at 1:40


Good idea, this will be better for more complicated searches which need more than *. JustRegisterMe Jul
13 '09 at 7:03

The code below expands on previous answers by showing a more complicated search case.
I had an application that was heavily controlled by a configuration file. In fact there were many
versions of the configuration each with different tradeoffs. So one configuration set would
result in a thorough work but would be very slow while another will be much faster but wont be
as thorough, etc. So the GUI would have a configuration combo box with options
corresponding to different configurations. Since I felt that the set of configurations will be
growing over the time, I did not want to hardcode the list of files and the corresponding options
(and their order) in the application but instead resorted to a file naming convention that would
convey all this information.
The naming convention that I used was as following. Files are located in directory
$MY_APP_HOME/dat. File name begins with my_config_ followed by the combo index
number, followed by the text for the combo item. For example: If the directory contained
(among others) files my_config_11_fast_but_sloppy.txt, my_config_100_balanced.txt,
my_config_3_thorough_but_slow.txt, my combo box would have options (in that order):
Thorough But Slow, Fast But Sloppy, Balanced.
So at runtime I needed to

23-11-2015 02:50 PM

linux - Search a folder for files like "/*tmp*.log" in Python - Stack Ove...

2 of 2

http://stackoverflow.com/questions/1090651/search-a-folder-for-files-l...

1. Find my configuration files in the directory


2. Extract a list of options from all the file names to put in the combo box
3. Sort options according to the index
4. Be able to get file path from the selected option
MyConfiguration class below does all the work in just a few lines of code (significantly fewer
that it took me to explain the purpose :-) and it can be used as following:
# populate my_config combobox
self.my_config = MyConfiguration()
self.gui.my_config.addItems(self.my_config.get_items())
# get selected file path
index = self.gui.my_config.currentIndex()
self.config_file = self.my_config.get_file_path_by_index(index);

Here is the MyConfiguration class:


import os, re
class MyConfiguration:
def __init__(self):
# determine directory that contains configuration files
self.__config_dir = '';
env_name = 'MY_APP_HOME'
if env_name in os.environ:
self.__config_dir = os.environ[env_name] + '/dat/';
else:
raise Exception(env_name + ' environment variable is not set.')
# prepare regular expression
regex = re.compile("^(?P<file_name>my_config_(?P<index>\d+?)_(?P<desc>.*?)
[.]txt?)$",re.MULTILINE)
# get the list of all files in the directory
file_names = os.listdir(self.__config_dir)
# find all files that are our parameters files and parse them into a list of
tuples: (file name, index, item_text)
self.__items = regex.findall("\n".join(file_names))
# sort by index as an integer
self.__items.sort(key=lambda x: int(x[1]))
def get_items(self):
items = []
for item in self.__items:
items.append( self.__format_item_text(item[2]))
return items
def get_file_path_by_index(self, index):
return self.__config_dir + self.__items[index][0]
def __format_item_text(self, text):
return text.replace("_", " ").title();

edited Sep 22 '12 at 14:25

answered Sep 22 '12 at 14:11


Leo
124

23-11-2015 02:50 PM