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的文件夹下进行修改。