How To List Only Files In a Directory Python

How To List Only Files In a Directory Python

to list only files in directory using python we have to os module. with python os module we can list only files in a directory.

Example 1:

import os
x=os.listdir()
for i in x:
    if os.path.isfile(i):
        print(i)

here we are using two functions in python os module those are os.listdir() and os.path.isfile().

os.listdir():   os.listdir() will list all files and directories in given path, here i didn't given any path so by default it will take current path i,e this python script file existed path.

or you can mention any path like os.listdir(r'C:\Users\devops\AppData\Local\Programs')

os.path.isfile():  os.path.isfile() will return true or false depends on file or directory. if it is a file it will return true if it is directory  it will return false.

in the example we are storing all the files and directories in variable(x) as a list, and by using for and if loop we are checking each item in the variable list is a file or not. If it is a file print that file name.

Output:

1-3.py
asf.txt
fsg.py
read-1.py
readme.txt
rfwr.py

Process finished with exit code 0

 

  • List Only Files In a Directory Python
  • list only files in a directory using python
  • python list only files in a directory
  • python print only files in a directory

Leave a Reply

Your email address will not be published. Required fields are marked *