Python implementation reads the file name of all files in the directory and saves it to the TXT file code

Source: Internet
Author: User
Code: (using Os.listdir)

Import Osdef 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")                    breakdef 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 subdirectory processing, each return three items are: The current recursive directory, all subdirectories under the current recursive directory, all the files in the current recursive directory.

import osdef listfilestotxt (dir,file,wildcard,recursion): exts =                Wildcard.split ("") for root, subdirs, files in Os.walk (dir): for name in files:for ext in exts: if (Name.endswith (EXT)): File.write (name + "\ n") break if (not RECU rsion): Breakdef 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 () 

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.