Python lists two levels of directories and saves them to List.txt

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.