Many times you need to list the files in each subdirectory under a directory and save them to list.txt so that you can traverse the subdirectory later
In image processing, this method is commonly used to process picture catalogs.
The directory structure is divided into 3 levels
RootDir
SubDir1
Pic1
Pic2
SubDir2
Pic1
Pic2
Want results List.txt
Under the RootDir directory
List.txt content is
SubDir1
SubDir2
Under the SUBDIR1/2 directory
List.txt content is
Pic1
Pic2
The code is:
Use the method to place the. Py in the current directory you want to extract
Import OS
Rootdir= ".";
Folderlist=os.listdir (RootDir);
#print (Folderlist)
Rootlist=open (rootdir+ "/list.txt", ' W ')
For subfolder in Folderlist:
#if subfolder[-3:]== ". Py":
#continue
Print (subfolder)
subpath=rootdir+ "/" +subfolder
If Os.path.exists (subfolder+ "/") ==false:
Print ("NO")
Continue
Rootlist.write (subfolder+ "\ n")
#print (subpath)
Subfolderlist=os.listdir (subpath)
#print (Subfolderlist)
listpath=subpath+ "/list.txt"
Listtxt=open (Listpath, ' W ')
For line in Subfolderlist:
If line[-4:]== ". txt":
Continue
Listtxt.write (line+ "\ n")
Listtxt.close ()
Rootlist.close ()
Python lists two levels of directories and saves them to List.txt