How to get only files in directory? [duplicate]

佐手、 提交于 2021-02-07 11:18:18

问题


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


回答1:


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)]

Or if you feel functional :D

files = filter(path.isfile, os.listdir(dirToScreens))



回答2:


"If you need a list of filenames that all have a certain extension, prefix, or any common string in the middle, use glob instead of writing code to scan the directory contents yourself"

import os
import glob

[name for name in glob.glob(os.path.join(path,'*.*')) if os.path.isfile(os.path.join(path,name))]


来源:https://stackoverflow.com/questions/21384232/how-to-get-only-files-in-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!