选择以给定字符串开头的文件 [英] Choose a file starting with a given string
本文介绍了选择以给定字符串开头的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在目录中,我有很多文件,它们的命名或多或少是这样的:
In a directory I have a lot of files, named more or less like this:
001_MN_DX_1_M_32
001_MN_SX_1_M_33
012_BC_2_F_23
...
...
在Python中,我必须编写一个代码,该代码从目录中选择以某个字符串开头的文件.例如,如果字符串为001_MN_DX
,则Python选择第一个文件,依此类推.
In Python, I have to write a code that selects from the directory a file starting with a certain string. For example, if the string is 001_MN_DX
, Python selects the first file, and so on.
我该怎么办?
推荐答案
尝试使用os.listdir
,os.path.join
和os.path.isfile
.
长格式(带有for循环),
Try using os.listdir
,os.path.join
and os.path.isfile
.
In long form (with for loops),
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]
在此处进行详细说明...
Check here for the long explanation...
这篇关于选择以给定字符串开头的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文