Python文本批处理

Python文本批处理

import os
import shutil

def text_edit_vhd(filepath):
    with open(filepath,'r+') as file_head:
        content = file_head.read()                    #修改文件并不是追加而是直接对一行进行重写,因此处理
                                                      #前需要先将要处理的行文本读取出来添加文本后再写入    
        file_head.seek(0,0)                           #修改文本处理位置
        file_head.write("`protect begin \n" + content)
        file_head.seek(0,2)
        file_head.write("\n`protect end ")

def text_edit_v(filepath):
    with open(filepath,'r+') as file_head:
        content = file_head.read()
        file_head.seek(0,0)
        file_head.write("`protect \n"+ content)
        file_head.seek(0,2)
        file_head.write(" \n`endprotect ")        


def add_text(srcpath):
    srcdirs = os.listdir(srcpath)
    for dir in srcdirs:
        if not os.path.isfile(os.path.join(srcpath, dir)): #判断dir属性,为文件或者文件夹
            add_text(os.path.join(srcpath, dir))
        else :
            if '.vhd' == dir[-4: ]:
                print("正在处理文件中,文件路径为:"+os.path.join(srcpath, dir))
                text_edit_vhd(os.path.join(srcpath, dir))
                print("文件处理完成!")
            elif '.v' == dir[-2:] :
                print("正在处理文件中,文件路径为:"+os.path.join(srcpath, dir))
                text_edit_v(os.path.join(srcpath, dir))
                print("文件处理完成!")


path = os.getcwd()
print('当前文件路径为:'+ path)
os.chdir('..')
root_path = os.getcwd()
handle_path = root_path + '\handle'
print('当前文件路径为:' + handle_path)
shutil.copytree(path,handle_path)
add_text(handle_path)
print("run done\n")

要更改修改的文本内容在text_edit_*函数中进行,本代码在修改文本时会先复制一份到自动新建handle的文件夹下进行修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值