In python How do I list all files of a directory ?

  • 3 Answer(s)

    Let us discuss about the solution:

        In pyhton , os.listdir() will get you everything that’s in a directory – files and directories.

    If we want just files, we could either filter this down using os.path:

    from os import listdir
    from os.path import isfile, join
    onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

    or else we could use os.walk() which will yield two lists for each directory it visits – splitting into files and dirs for us. If we only want the top directory you can just break the first time it yields

    from os import walk
    f = []
    for (dirpath, dirnames, filenames) in walk(mypath):

    Finally, as that example shows, adding one list to another we can either use .extend() or

    >>> q = [1, 2, 3]
    >>> w = [4, 5, 6]
    >>> q = q + w
    >>> q
    [1, 2, 3, 4, 5, 6]

    .extend() is mostly preferable

    Answered on December 20, 2018.
    Add Comment

    The solution for this problem is:

        It is preferable to use glob module, as it does pattern matching and expansion

    import glob

    Then it will return as

    ['/home/xyz/file1.txt', '/home/xyz/file2.txt', .... ]
    Answered on December 20, 2018.
    Add Comment

    The solution for the given statement is,

        In python

    import os

    it will return all the files and directories in “somedirectory”

    Answered on December 20, 2018.
    Add Comment

  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.