选择以给定字符串开头的文件

thi*_*ick 39 python file

在一个目录中,我有很多文件,或多或少地命名为:

001_MN_DX_1_M_32
001_MN_SX_1_M_33
012_BC_2_F_23
...
...
Run Code Online (Sandbox Code Playgroud)

在Python中,我必须编写一个代码,从目录中选择以某个字符串开头的文件.例如,如果字符串是001_MN_DX,Python选择第一个文件,依此类推.

我该怎么做?

Mar*_*arn 50

import os
prefixed = [filename for filename in os.listdir('.') if filename.startswith("prefix")]
Run Code Online (Sandbox Code Playgroud)


pra*_*nsg 44

尝试使用os.listdir,os.path.joinos.path.isfile.
长形式(带有for循环),

import os
path = 'C:/'
files = []
for i in os.listdir(path):
    if os.path.isfile(os.path.join(path,i)) and '001_MN_DX' in i:
        files.append(i)
Run Code Online (Sandbox Code Playgroud)

代码,列表推导是

import os
path = 'C:/'
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         '001_MN_DX' in i]
Run Code Online (Sandbox Code Playgroud)

点击此处查看详细说明......

  • 我会将i`中的`和'001_MN_DX'替换为`和i.startswith('001_MN_DX')`因为文件'E_001_MN_DX.txt'也会匹配原始代码. (11认同)

小智 15

您可以使用模块glob,它遵循 Unix shell 模式匹配规则。 查看更多。

from glob import glob

files = glob('*001_MN_DX*')
Run Code Online (Sandbox Code Playgroud)


Xia*_*ong 8

import os, re
for f in os.listdir('.'):
   if re.match('001_MN_DX', f):
       print f
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用os模块列出目录中的文件。

例如:查找当前目录中名称以001_MN_DX开头的所有文件

import os
list_of_files = os.listdir(os.getcwd()) #list of files in the current directory
for each_file in list_of_files:
    if each_file.startswith('001_MN_DX'):  #since its all type str you can simply use startswith
        print each_file
Run Code Online (Sandbox Code Playgroud)