python 批量修改文件内容示例

#coding=utf-8
import os

# for root, dirs, files in os.walk("./"): 
#   for dir in dirs: 
#       print(os.path.join(root,dir))
#   for file in files: 
#       print(os.path.join(root,file))


def listdir(path, list_name, iscontent):
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if os.path.isdir(file_path):
            _isC = False
            if os.path.basename(file_path) == "content": #指定目录
                _isC = True
            listdir(file_path, list_name, _isC)
        else:
            if iscontent:
                list_name.append(file_path)
            # print(file_path)

list = []
listdir("./", list, False)

print(list)

for i in range(0, len(list)):
    cont = ""
    with open(list[i], 'r') as f:
        # print(f.read())
        cont = f.read() #读出内容

    cont = "内容前" + cont + "内容后"

    fh = open(list[i], 'w')
    fh.write(cont)
    fh.close()

你可能感兴趣的:(python 批量修改文件内容示例)