There are two functions under the OS module:
Os.walk ()
Os.listdir ()
1 #-*-coding:utf-8-*-2 3 ImportOS4 5 deffile_name (file_dir):6 forRoot, dirs, filesinchOs.walk (file_dir):7 Print(Root)#Current directory path8 Print(dirs)#all subdirectories under current path9 Print(Files)#all non-directory sub-Files under current path
The output format is:
Current file directory path
The current path under the file directory (if present, does not exist or [])
Non-directory sub-file under current path (file name only for child files)
Sub-file 1 path
Sub-file directory under sub-file 1
Non-directory sub-Files under sub-file 1
Sub-file 2 path
Sub-file directory under sub-file 2
Non-directory sub-Files under sub-file 2
1 #-*-coding:utf-8-*-2 3 ImportOS4 5 deffile_name (file_dir):6L=[] 7 forRoot, dirs, filesinchOs.walk (file_dir):8 forFileinchFiles:9 ifOs.path.splitext (file) [1] = ='. JPEG': Ten L.append (Os.path.join (root, file)) One returnL A - - #where the Os.path.splitext () function splits the path into file name + extension
1 #-*-coding:utf-8-*-2 ImportOS3 4 defListdir (Path, list_name):#List of incoming stores5 forFileinchOs.listdir (path):6File_path =os.path.join (path, file)7 ifOs.path.isdir (file_path):8 Listdir (File_path, List_name)9 Else: TenList_name.append (File_path)
Recursively outputs all non-directory sub-files under the current path
Python Gets the file directory and filename in the current directory