uses two methods of os.walk () and os.listdir () to get the name of the file under the specified folder.

one, os.walk ()

module OS, walk () function can traverse all files in the folder.

 os.walk (top, topdown=Ture, onerror=None, followlinks=False) 

the function can get a three yuan tupple (dirpath, dirnames, filenames).


  1. dirpath:string, the meaning of parameters to represent the path directory;
  2. < li>dirnames:list, containing the current dirpath path of all the sub directory name (not included in the directory path


  3. filenames:list,) contains non directory sub file all the current dirpath path name (not included in the directory path).

, dirnames and filenames do not contain path information for the full path, you can use the os.path.join (dirpath, dirnames)

 code given below; # -*- coding: UTF-8 -*- import OS def file_name (file_dir): for root, dirs, files in os.walk (file_dir): Print (root) # current directory path print (dirs) # current path all the subdirectories under the print (files) # current path all the sub file directory 


when needed for specific types of files, the code is as follows:

 coding: UTF-8 # -*- -*- import OS def file_name (file_dir): L=[] for root, dirs, files in os.walk (file_dir): for file in files: if os.path.splitext (file) [1] = ='.jpeg': L.append (os.path.join (root, file)) Return L 

, where os.path.splitext () function splits the path into file name + extension, for example, os.path.splitext ("E:/lena.jpg") will get "E:/lena" + ".Jpg".

two, os.listdir ()

os.listdir () function gets the file name under the current path, not the files in the subdirectory, all need to use recursive method to get all the file names. Given the direct

code, the function returns the type '.Jpeg' file name:

 coding: UTF-8 # -*- -*- import OS def listdir (path, list_name): for file in os.listdir (path): file_path = os.path.join (path, file) if os.path.isdir (file_path): listdir (file_path, list_name) elif os.path.splitext (file_path) [1]=='.jpeg': list_name.append (file_path) 

beginner python, made some mistakes, wasting a lot of time, we must ensure that the code of the four indent, pay attention to enter the next line and not four indent; there is one point in the command prompt window (Windows) using the Python interpreter runs for the first time the code, modify the source code, if run again need to exit back into the python interpreter, Or you will still run the first code that has been executed.

is the whole content of this article, I hope to help you, and hope that you can support a lot of scripting home.

you might be interested in this article: "

This concludes the body part

This paper fixed link: | Script Home | +Copy Link

Article reprint please specify:Python gets the method of the file name under the specified folder | Script Home

You may also be interested in these articles!