Python 选择以给定字符串开头的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15312953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Choose a file starting with a given string
提问by this.is.not.a.nick
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
...
...
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.
在 Python 中,我必须编写一个代码,从目录中选择一个以特定字符串开头的文件。例如,如果字符串是001_MN_DX,Python 选择第一个文件,依此类推。
How can I do it?
我该怎么做?
采纳答案by pradyunsg
Try using os.listdir,os.path.joinand os.path.isfile.
In long form (with for loops),
尝试使用os.listdir,os.path.join和os.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)
Code, with list-comprehensions is
带有列表推导式的代码是
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 herefor the long explanation...
检查这里的长篇解释...
回答by dawnsong
import os, re
for f in os.listdir('.'):
if re.match('001_MN_DX', f):
print f
回答by sansxpz
You can use the os module to list the files in a directory.
您可以使用 os 模块列出目录中的文件。
Eg: Find all files in the current directory where name starts with 001_MN_DX
例如:查找当前目录中名称以 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
回答by Marc Laugharn
import os
prefixed = [filename for filename in os.listdir('.') if filename.startswith("prefix")]
回答by M Gui
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

