import os
print("Python Program to print list the files in a directory.")
Direc = input(r"Enter the path of the folder: ")
print(f"Files in the directory: {Direc}")
files = listdir(Direc)
files = [f for f in files if os.path.isfile(Direc+'/'+f)] #Filtering only the files.
print(*files, sep="\n")
Asked
Active
Viewed 74 times
1

Daniel Hao
- 4,922
- 3
- 10
- 23

Rahul Kumar
- 11
- 1
-
Why not use *pathlib* `Path` instead? – Daniel Hao Dec 29 '22 at 13:16
-
Does this answer your question? [How do I list all files of a directory?](https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) – Giordano Dec 29 '22 at 13:17
-
Since Python 3.6+ it has *pathlib* to handle the file ops. (OOP concept) - it's recommended way. – Daniel Hao Dec 29 '22 at 13:23
1 Answers
2
You can use the isfile()
function from the os.path
module to check whether an element is a file or a directory:
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
Or search for other alternatives as well here.

Michael M.
- 10,486
- 9
- 18
- 34

Favkes
- 23
- 6