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 3 in Python by Hari
12 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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 3 by Omkar
• 65,810 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,710 points
37 views
0 votes
1 answer

How to Reverse a list in Python

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

answered Sep 28, 2018 in Python by SDeb
• 9,300 points
44 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,500 points
35 views
0 votes
1 answer

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

Use os.rename(src, dst) to rename or move a file ...READ MORE

answered Nov 23, 2018 in Python by ariaholic
• 7,320 points
57 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 920 points
18 views
+4 votes
6 answers
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 3 in Python by Omkar
• 65,810 points
73 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 3 in Python by Omkar
• 65,810 points
11 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.