批量文件文本替换

使用说明:

将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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值