Python implements replacement strings in multiple files __python

Source: Internet
Author: User
Import string
import os
import struct
import re
import fileinput
import Fnmatch

Fileinput and Fnmatch Two module are mainly used here

Fnmatch.fnmatch is primarily used to determine the suffix name of a file

Fnmatch. Fnmatch (filename, pattern) for pattern:

*.txt→txt file

*.doc→doc file

*.*→ All Files

The fileinput in the inplace=true indicates that the output is redirected to the file. This way all print output points to a file.

def walkdir (directory, ext= ' *.* ', topdown=true):
    filearray = [] for
    root, dirs, files in Os.walk (directory, Topdo WN): For
        name in files:
            if Fnmatch.fnmatch (name, ext):
                filearray.append (Os.path.abspath os.path.join ( root, name)) return
    Filearray

def replaceinfile (filename, strfrom, Strto): For line in
    Fileinput.input ( FileName, inplace=true):
        if Re.search (Strfrom, line): Line
            = Line.replace (strfrom, strto)
        print line,

if __name__ = = ' __main__ ': for
    filename in Walkdir ('. ', ' *.txt '):
        replaceinfile (filename, ' abc ', ' CBA ')

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.