Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Programming»Python»How to List All files in a Directory using Python

    How to List All files in a Directory using Python

    By RahulMay 2, 20191 Min Read

    This tutorial contains a sample Python script for listing all available files in a directory. This script will ignore all directories and subdirectories.

    Advertisement

    The Python listdir() function available under os package is used to listing all content of a directory. So you can simply print the results of the listdir() function. This will show files as well as directories. This function accepts an argument as a directory location.

    1
    2
    >>> from os import listdir
    >>> listdir('/home/rahul')

    Here our requirement is to list only files (not directories). So program needs to loop through the array resulted by listdir() and print only files ignoring rest.

    1
    2
    3
    4
    5
    6
    7
    from os import listdir
    from os.path import isfile, join
     
    dirName = '/home/rahul'
    fileNames = [f for f in listdir(dirName) if isfile(join(dirName, f))]
     
    print (fileNames)

    Save the above script in a file (eg: myScript.py), Then execute this Python script on command line. You will see the results like below:

    python myScript.py
    

    Output:

    ['.bash_logout', '.bashrc', 'testfile.txt', '.profile', 'index.html']
    

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    How to Create and Read List in Python

    Python Program to Add Two Numbers

    Files and Directory Handling in Python

    Files and Directory Handling in Python

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Configure Postfix to Use Gmail SMTP on Ubuntu & Debian
    • PHP Arrays: A Beginner’s Guide
    • Deploying Flask Application on Ubuntu (Apache+WSGI)
    • OpenSSL: Working with SSL Certificates, Private Keys and CSRs
    • How to Create and Read List in Python
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.