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

2024-05-15 06:15:48 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个目录中,我有很多文件,名称大致如下:

001_MN_DX_1_M_32
001_MN_SX_1_M_33
012_BC_2_F_23
...
...

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

我该怎么做?


Tags: 文件字符串代码目录名称bcmnsx
4条回答
import os, re
for f in os.listdir('.'):
   if re.match('001_MN_DX', f):
       print f

尝试使用os.listdiros.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)

代码,带有列表理解是

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]

请检查here以获取详细解释。。。

import os
prefixed = [filename for filename in os.listdir('.') if filename.startswith("prefix")]

相关问题 更多 >

    热门问题