我有一个文件名的一部分列表,对于每个我想要浏览与该部分匹配的目录中的文件并返回文件名

时间:2016-09-04 01:12:09

标签: python

所以,假设我有一个包含大量文件名的目录。 例如:

标量积或点积(印地语)-fodZTqRhC24.m4a
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a
点产品简介-X5DifJW0zek.m4a

现在假设我有一个列表,只有键,它们位于文件名的末尾:

['fodZTqRhC24', 'Wvhn_lVPiw0, 'X5DifJW0zek']

如何遍历我的列表进入该目录并搜索包含该密钥的文件名,然后返回文件名?

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:1)

我想到了,我认为我正在使它比正则表达式更难。很抱歉没有先尝试。我这样做了:

audio = ['Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a',
'An Introduction to the Dot Product-X5DifJW0zek.m4a',
'AP Physics C - Dot Product-Wvhn_lVPiw0.m4a']   

keys = ['fodZTqRhC24', 'Wvhn_lVPiw0', 'X5DifJW0zek']   

file_names = []
for Id in keys:
    for name in audio:
        if Id in name:
            file_names.append(name)

combined = zip(keys,file_names)
combined            

答案 1 :(得分:0)

以下是一个例子:

ls:给定目录中的文件列表

names:要搜索的字符串列表

import os
ls=os.listdir("/any/folder")
n=['Py', 'sql']
for file in ls:
   for name in names:
     if name in file:
       print(file)

结果:

.PyCharm50
.mysql_history
zabbix2.sql
.mysql
PycharmProjects
zabbix.sql

答案 2 :(得分:0)

假设您知道要查找的目录,可以尝试以下方法:

import os

to_find = ['word 1', 'word 2']          # list containing words that you are searching for
all_files = os.listdir('/path/to/file') # creates list with files from given directory

for file in all_files:    # loops through all files in directory
    for word in to_find:  # loops through target words
        if word in file:
            print file    # prints file name if the target word is found

我在包含这些文件的目录中对此进行了测试:

Helper_File.py
forms.py
runserver.py
static
app.py
templates

...我将to_find设置为['runserver', 'static'] ...

当我运行此代码时,它返回:

runserver.py
static

为了将来参考,您应该在Stackoverflow上发布问题之前至少尝试某种方法来解决问题。如果您无法提供尝试证明,那么人们通常不会像这样帮助您。

答案 3 :(得分:0)

这是一种方法,可以根据文字的位置选择匹配的天气。

import os
def scan(dir, match_key, bias=2):
    '''
        :0 startswith
        :1 contains
        :2 endswith
        '''

    matches = []
    if not isinstance(match_key, (tuple, list)):
        match_key = [match_key]

    if os.path.exists(dir):
        for file in os.listdir(dir):
            for match in match_key:
                if file.startswith(match) and bias == 0 or file.endswith(match) and bias == 2 or match in file and bias == 1:
                    matches.append(file)
                    continue
    return matches

print scan(os.curdir, '.py'