How to get only files in directory?

Question:

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

Asked By: user2817200

||

Answers:

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 😀

files = filter(path.isfile, os.listdir(dirToScreens))
Answered By: Paulo Bu

“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))]
Answered By: juankysmith
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.