Python reads all file names under the specified directory and its subdirectories
Target
As you accumulate more and more files on your disk, searching for a file is too slow and memory-using Windows. Therefore, I want to find a file name that can get all the files in the specified directory, as a kind of document management method of library index directory.
This is accomplished by using the Python Os.walk () function to traverse all files in the specified directory and all subdirectories. Implemented using the Python 3.6 version.
The Walk () function returns the directory tree Builder (iterator). The file name in the directory tree is generated by traversing the directory from the top down. For each directory in the tree at the top of the root directory (including the top itself), it produces a 3-tuple (dirpath,dirnames,filenames). Dirpath is a string, which is the path to the directory.
Dirnames is the name list of the Dirpath neutron directory. Filenames is a list of dirpath file names in the Central African directory. However, the name in the list does not contain a path, and to get a full path (starting from the top) to a file or directory in Dirpath, perform os.path.join (Dirpath,name). See the Python standard library Documentation Os.walk () for more details.
The implementation code is as follows
Import OS
def all_path (dirname):
filelistlog = dirname + "\\filelistlog.txt" # Save file path
postfix = set ([' PDF ', ' Doc ', ' docx ', ' epub ', ' txt ', ' xlsx ', ' DjVu ', ' chm ', ' ppt ', ' pptx '] # Set the file format to save for
Maindir, SubDir, File_ Name_list in Os.walk (dirname): for
filename in file_name_list:
Apath = Os.path.join (maindir, filename)
if True: # saves all file names. To keep the file name in the specified file format note the sentence
#if apath.split ('. ') [-1] in postfix: # match suffix, save only the selected file format. To save all files, note the sentence
try: with
open (Filelistlog, ' A + ') as fo:
fo.writelines (Apath)
fo.write (' \ n ')
except:
pass # So all exceptions can be ignored
if __name__ = = ' __main__ ':
dirpath = "D:" # Specify root directory
All_ Path (Dirpath)
The program runs to save all file names as filelistlog.txt files in the specified directory.