Python 如何只获取目录中的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21384232/
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
How to get only files in directory?
提问by user2817200
I have this code:
我有这个代码:
allFiles = os.listdir(myPath)
for module in allFiles:
if 'Module' in module: #if the word module is in the filename
dirToScreens = os.path.join(myPath, module)
allSreens = os.listdir(dirToScreens)
Now, all works well, I just need to change the line
现在,一切正常,我只需要更改线路
allSreens = os.listdir(dirToScreens)
to get a list of just files, not folders. Therefore, when I use
获取仅包含文件而不是文件夹的列表。因此,当我使用
allScreens [ f for f in os.listdir(dirToScreens) if os.isfile(join(dirToScreens, f)) ]
it says
它说
module object has no attribute isfile
NOTE: I am using Python 2.7
注意:我使用的是Python 2.7
采纳答案by Paulo Bu
You can use os.path.isfilemethod:
您可以使用os.path.isfile方法:
import os
from os import path
files = [f for f in os.listdir(dirToScreens) if path.isfile(f)]
Or if you feel functional :D
或者,如果您觉得功能强大:D
files = filter(path.isfile, os.listdir(dirToScreens))
回答by juankysmith
"If you need a list of filenames that all have a certain extension, prefix, or any common string in the middle, use globinstead of writing code to scan the directory contents yourself"
“如果您需要一个文件名列表,这些文件名都具有特定的扩展名、前缀或中间的任何常见字符串,请使用glob而不是自己编写代码来扫描目录内容”
import os
import glob
[name for name in glob.glob(os.path.join(path,'*.*')) if os.path.isfile(os.path.join(path,name))]

