Home  >  Article  >  Backend Development  >  Introduction to how to use python to replace file names and file contents in a folder

Introduction to how to use python to replace file names and file contents in a folder

高洛峰
高洛峰Original
2017-03-20 10:19:161847browse

Example effect:

1. Replace the name of the folder and subfolder under a folder from OldStrDir to NewStrDir;

2. Replace The names of all files in folders and subfolders under a certain folder change from OldStrFile to NewStrFile;

3. Replace the contents of all files in folders and subfolders under a certain folder by OldStrContent becomes NewStrContent;

Corresponding code:

# -*- coding: UTF-8 -*-

import os
import re

#replace dir name
def replaceDirName(rootDir,oldStr,newStr):
    for parent,dirNames,fileNames in os.walk(rootDir,topdown=False):
        for dirName in dirNames:
            if oldStr in dirName:
                dirNameOld = os.path.join(parent,dirName)
                dirNameNew = os.path.join(parent,dirName.replace(oldStr,newStr))
                print(dirNameOld  + ' --> ' +  dirNameNew)
                os.rename(dirNameOld,dirNameNew)
            
            
#replace file name
def replaceFileName(rootDir,oldStr,newStr):
    for parent,dirNames,fileNames in os.walk(rootDir):
        for fileName in fileNames:
            if oldStr in fileName:
                fileNameOld = os.path.join(parent,fileName)
                fileNameNew =  os.path.join(parent,fileName.replace(oldStr,newStr))
                print(fileNameOld  + ' --> ' +  fileNameNew)
                os.rename(fileNameOld,fileNameNew)
            
#replace file content name
def replaceFileContent(rootDir,oldStr,newStr):
    for parent,dirNames,fileNames in os.walk(rootDir):
        for fileName in fileNames:
            fileObj = os.path.join(parent,fileName)
            f = open(fileObj,'r+')
            all_the_lines=f.readlines()
            f.seek(0)
            f.truncate()
            for line in all_the_lines:
                f.write(line.replace(oldStr,newStr))    
            f.close()  


def main():
    rootDir = "D:/D"
    oldStr = "CustomerType"
    newStr = "CustomerAttr"

    replaceDirName(rootDir,oldStr,newStr)
    replaceFileName(rootDir,oldStr,newStr)
    replaceFileContent(rootDir,oldStr,newStr)

if __name__=='__main__':
    main()

The above is the detailed content of Introduction to how to use python to replace file names and file contents in a folder. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn