在Python中查找文件名类似于"/*tmp*.log"的文件
正如标题所说,我在使用Linux系统,这个文件夹里可能有多个文件。我想找到一个文件,它的名字里包含 *tmp*.log
(这里的 *
代表任何内容!)。就像我在Linux命令行中做的那样。
3 个回答
0
下面的代码扩展了之前的回答,展示了一个更复杂的搜索案例。
我有一个应用程序,它的运行主要依赖于一个配置文件。实际上,这个配置文件有很多版本,每个版本都有不同的优缺点。比如说,一个配置可能会让程序运行得很彻底,但速度很慢;而另一个配置则可能运行得快,但不够全面,等等。因此,程序的界面上有一个下拉框,里面有不同配置的选项。因为我觉得配置的数量会随着时间增加,所以我不想在程序里死死写死这些文件名和对应的选项(以及它们的顺序),而是采用了一种文件命名规则来传达这些信息。
我使用的命名规则如下:文件存放在目录 $MY_APP_HOME/dat 中。文件名以 my_config_ 开头,后面跟着下拉框的索引号,再后面是下拉框选项的文本。例如:如果这个目录里有(除了其他文件) my_config_11_fast_but_sloppy.txt、my_config_100_balanced.txt 和 my_config_3_thorough_but_slow.txt 这些文件,那么我的下拉框里的选项会是(按这个顺序):彻底但慢、快速但粗糙、平衡。
所以在程序运行时,我需要:
- 找到目录里的配置文件
- 从所有文件名中提取出选项列表,放到下拉框里
- 根据索引对选项进行排序
- 能够从选中的选项获取文件路径
下面的 MyConfiguration 类用几行代码完成了所有这些工作(比我解释目的所花的时间少得多 :-)),可以这样使用:
# 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);
这是 MyConfiguration 类:
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();
2
使用 glob 方法更简单,不过为了全面起见,你也可以用 os.listdir 和正则表达式来检查:
import os
import re
dirEntries = os.listdir(path/to/dir)
for entry in dirEntries:
if re.match(".*tmp.*\.log", entry):
print entry
12
使用 glob
模块。
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']