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, 2019 in Python by Hari
61 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 3, 2019 by Omkar
• 69,030 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,780 points
210 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
• 13,250 points
179 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,520 points
513 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 28 in Python by The real slim shady
2,043 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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,344 views
0 votes
0 answers
+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, 2019 in Python by Omkar
• 69,030 points
981 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, 2019 in Python by Omkar
• 69,030 points
68 views