Get file names in a folder using Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ShaheerAbdulrahiman
    New Member
    • Apr 2007
    • 1

    #1

    Get file names in a folder using Python

    Hi All,

    How can we get the file names in a folder using python?

    Could you please help me....?

    Thanks and Regards,
    Shaheer
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by ShaheerAbdulrah iman
    Hi All,

    How can we get the file names in a folder using python?

    Could you please help me....?

    Thanks and Regards,
    Shaheer
    We did this exercise several months ago. I just happened to have the code handy! I commented out the part you may not need.
    Code:
    import os
    def dir_list2(dir_name, *args):
        fileList = []
        for file in os.listdir(dir_name):
            dirfile = os.path.join(dir_name, file)
            if os.path.isfile(dirfile):
                if len(args) == 0:
                    fileList.append(dirfile)
                else:
                    if os.path.splitext(dirfile)[1][1:] in args:
                        fileList.append(dirfile)
            '''
            elif os.path.isdir(dirfile):
                print "Accessing directory:", dirfile
                fileList += dir_list2(dirfile, *args)
            '''
        return fileList
    
    if __name__ == '__main__':
        fileList = dir_list2('path_to_directory')
        for f in fileList:
            print f
    ...and the simple way:
    Code:
    >>> import os
    >>> os.listdir('path to directory')

    Comment

    Working...