如何只获取目录中的文件? [英] How to get only files in directory?
本文介绍了如何只获取目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码:
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)) ]
说
module object has no attribute isfile
注意:我正在使用 Python 2.7
推荐答案
You can use os.path.isfile
method:
import os
from os import path
files = [f for f in os.listdir(dirToScreens) if path.isfile(f)]
或者,如果您觉得功能正常:D
Or if you feel functional :D
files = filter(path.isfile, os.listdir(dirToScreens))
这篇关于如何只获取目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文