Error while using listdir in Python

后端 未结 8 838
小蘑菇
小蘑菇 2020-12-10 04:14

I\'m trying to get the list of files in a particular directory and count the number of files in the directory. I always get the following error:

WindowsError         


        
8条回答
  •  有刺的猬
    2020-12-10 05:09

    If you just want to see all the files in the directory where your script is located, you can use os.path.dirname(sys.argv[0]). This will give the path of the directory where your script is.

    Then, with fnmatch function you can obtain the list of files in that directory with a name and/or extension specified in the filenamevariable.

    import os,sys
    from fnmatch import fnmatch
    
    directory = os.path.dirname(sys.argv[0])    #this determines the directory
    file_name= "*"                              #if you want the python files only, change "*" to "*.py"
    
    for path, subdirs, files in os.walk(directory):
        for name in files:
            if fnmatch(name, file_name):
                print (os.path.join(path, name))
    

    I hope this helps.

提交回复
热议问题