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, 2019 in Python by ana1504.k
• 7,910 points
9,805 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, 2019 by SDeb
• 13,300 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
• 58,020 points
987 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
• 58,020 points
1,306 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 24, 2018 in Python by Aryya
• 500 points
829 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,466 views
0 votes
1 answer
0 votes
1 answer

How to set NotebookApp.iopub_data_rate_limit and others NotebookApp settings in JupyterHub?

Open the command line and enter jupyter notebook ...READ MORE

answered Jun 10, 2019 in Python by SDeb
• 13,300 points
13,100 views
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
• 13,300 points
941 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP