Python to read the file name of all files in the directory and save to TXT file code _python

Source: Internet
Author: User

Code: (using Os.listdir)

Copy Code code as follows:

Import OS

def listfilestotxt (dir,file,wildcard,recursion):
exts = Wildcard.split ("")
Files = Os.listdir (dir)
For name in Files:
Fullname=os.path.join (Dir,name)
if (Os.path.isdir (FullName) & recursion):
Listfilestotxt (fullname,file,wildcard,recursion)
Else
For ext in exts:
if (Name.endswith (EXT)):
File.write (name + "\ n")
Break

Def Test ():
Dir= "J:\\1"
Outfile= "Binaries.txt"
Wildcard = ". txt. exe. dll. Lib"

File = open (outfile, "w")
If not file:
Print ("Cannot open the file%s for writing"% outfile)

Listfilestotxt (Dir,file,wildcard, 1)

File.close ()

Test ()

code: (using Os.walk) walk recursively to the directory and subdirectories, each returned three entries: the current recursive directory, all subdirectories under the current recursive directory, and all files under the current recursive directory.

Copy Code code as follows:

Import OS

Def listfilestotxt (dir,file,wildcard,recursion):
    exts = Wildcard.split ("")
     for Root, subdirs, files in Os.walk (dir):
        to name in files:< br>             for ext in exts:
                 if (name.endswith (EXT)):
                     File.write (name + \ n)
                     Break
        if (not recursion):
             Break

Def Test ():
Dir= "J:\\1"
Outfile= "Binaries.txt"
Wildcard = ". txt. exe. dll. Lib"

File = open (outfile, "w")
If not file:
Print ("Cannot open the file%s for writing"% outfile)

Listfilestotxt (Dir,file,wildcard, 0)

File.close ()

Test ()

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.