how to find files and skip directories in os.listdir

0 votes
I have been using os.listdir and it works fine, but I get sub-directories in the list also. I don't want that as I need only files.

What function do I need to use for that ? Can anyone suggest me any other way?
Mar 6 in Python by ana1504.k
• 7,390 points
52 views

1 answer to this question.

0 votes
You need to filter out directories; os.listdir() lists all names in a given path. You can use os.path.isdir() for this:

basepath = '/path/to/directory'
for fname in os.listdir(basepath):
    path = os.path.join(basepath, fname)
    if os.path.isdir(path):
        # skip directories
        continue
 

os.walk() does the same work under the hood; unless you need to recurse down subdirectories, you don't need to use os.walk() here.
answered Mar 6 by SDeb
• 12,200 points

Related Questions In Python

0 votes
0 answers
0 votes
1 answer

How to find index from raw and column in python?

You probably want to use np.ravel_multi_index: import numpy as ...READ MORE

answered Sep 12, 2018 in Python by Priyaj
• 56,160 points
58 views
0 votes
1 answer

How to find index from raw and column in python?

You probably want to use np.ravel_multi_index: import numpy as ...READ MORE

answered Sep 24, 2018 in Python by Priyaj
• 56,160 points
26 views
0 votes
0 answers

How to mix read() and write() on Python files in Windows

It appears that a write() immediately following a read() on a ...READ MORE

Oct 23, 2018 in Python by Aryya
• 500 points
31 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 124 views
0 votes
1 answer
0 votes
1 answer

How to use a global variable in function?

The global variable can be used in ...READ MORE

answered Sep 27, 2018 in Python by SDeb
• 12,200 points
17 views