1
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")
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23

1 Answers1

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