在一个目录中,我有很多文件,其命名或多或少如下:
001_MN_DX_1_M_32
001_MN_SX_1_M_33
012_BC_2_F_23
...
...
在Python中,我必须编写一段代码,从目录中选择以某个字符串开头的文件。例如,如果字符串是
001_MN_DX
,Python 将选择第一个文件,依此类推。
我该怎么做?
import os
prefixed = [entry for entry in os.listdir('.') if entry.startswith("prefix") and os.path.isfile(entry)]
尝试使用
os.listdir
、os.path.join
和 os.path.isfile
。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]
查看此处了解详细说明...
您可以使用模块glob,它遵循Unix shell规则进行模式匹配。 查看更多。
from glob import glob
files = glob('*001_MN_DX*')
import os, re
for f in os.listdir('.'):
if re.match('001_MN_DX', f):
print f
您可以使用 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
import os
for filename in os.listdir('.'):
if filename.startswith('criteria here'):
print filename #print the name of the file to make sure it is what
you really want. If it's not, review your criteria
#Do stuff with that file
使用较新的
pathlib
模块,请参阅链接:
from pathlib import Path
myDir = Path('my_directory/')
fileNames = [file.name for file in myDir.iterdir() if file.name.startswith('prefix')]
filePaths = [file for file in myDir.iterdir() if file.name.startswith('prefix')]
pathlib.Path
,如下所示:
Path(root_dir).glob('*001_MN_DX*')
如果您需要在子目录中进行递归通配:
Path(root_dir).glob('**/*001_MN_DX*')