How to list only files in a directory

0 votes

How can I list only files in a directory ignoring the sub-directories? I am using listdir method but it lists directories also:

import os
print (listdir("/home/Papers/"))

This prints directories also. I want it to print only files

Feb 4, 2019 in Python by Hari
786 views

1 answer to this question.

0 votes

Before printing, you can use a check to print the name only if it is a file. Something like this:

import os
from os import path
print(f for f in os.listdir('/home') if path.isfile(f))
answered Feb 4, 2019 by Omkar
• 69,220 points

Related Questions In Python

0 votes
1 answer

How to Print a List in Python

ou are using Python 2.x syntax with ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
1,038 views
0 votes
1 answer

How to Reverse a list in Python

You can use the reversed function in ...READ MORE

answered Sep 29, 2018 in Python by SDeb
• 13,300 points
818 views
0 votes
1 answer

List comprehension on a nested list - How to do it in Python?

Not sure what your desired output is, ...READ MORE

answered Nov 21, 2018 in Python by Nymeria
• 3,560 points
1,495 views
0 votes
2 answers

How can I rename multiple files in a certain directory using Python?

import os from optparse import OptionParser, Option class MyOption ...READ MORE

answered Jul 29, 2020 in Python by The real slim shady
4,693 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,398 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,008 views
0 votes
1 answer

How to list only text files in a directory using python?

Well, you are using a complex way. ...READ MORE

answered Feb 4, 2019 in Python by Omkar
• 69,220 points
2,712 views
0 votes
1 answer

How to list files/directories in python

You can use the os module to list the ...READ MORE

answered Feb 4, 2019 in Python by Omkar
• 69,220 points
754 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