使用说明:
将replace.py和replace.cmd文件置于待替换文本文件目录下,修改replace.dat,此处为需要替换内容,执行replace.cmd,生成target目录,里面为替换后文件
replace.py:
#!/usr/bin/env Python
# coding=utf-8
import os
import tkinter.messagebox
from tkinter import *
import chardet
#获取文件扩展名
def file_extension(path):
return os.path.splitext(path)[1]
#获取文件编码
def getCode(path):
f = open(path,'rb')
data = f.read()
f.close()
return chardet.detect(data)['encoding']
words = []
arr = []
path = os.getcwd()
#创建target目录
isExists=os.path.exists(path + "\\target")
if not isExists:
os.makedirs(path + "\\target")
lst = os.listdir(path) #列出文件夹下所有的目录与文件
for i in range(0,len(lst)):
p = os.path.join(path,lst[i])
if os.path.isfile(p):
if (file_extension(p)).lower() == '.txt':
arr.append(lst[i])
path = path + "\\"
with open(path+'replace.dat','r',encoding='utf-8') as f3:
for i in f3:
words.append(i)
for f in arr:
with open(path+f,'r',encoding=getCode(path+f)) as f1,open(path+'target\\'+f,'w',encoding='utf-8') as f2:
for i in f1:
#替换操作
#todo
for word in words:
w1 = word.split(',')[0].strip()
w2 = word.split(',')[1].strip()
i = i.replace(w1,w2)
f2.write(i)
tkinter.messagebox.showinfo('提示', '替换成功')
replace.cmd:
python replace.py
replace.dat:
a, A
b,B
c, C
环境:
Python 3.7.0 + chardet-3.0.4