新手菜鸟求助一个查找替换的问题
我想把指定目录所有文件里有rep_word1 ,rep_word2 的内容,改成new_word1,new_word2的内容,求高手指教如果高手们能把我指定目录下的所有子目录里的文件的内容都按上面要求替换掉就更好
import os
all_files = os.listdir('E:\\Requirement\\需求分析')
rep_word1 = '电子交易系统' #需要被替换的词
new_word1 = '大宗商品交易管理系统'#替换后的词
rep_word2 = 'E-commerce' #需要被替换的词
new_word2 = 'Trading Platform' #替换后的词
for each_file in all_files:
f_read = open(each_file)
print(f_read)
content1 = []
content2 = []
count = 0
for eachline in f_read:
if rep_word1 in eachline1:
eachline = eachline.replace(rep_word1,new_word1)
content1.append(eachline)
if rep_word2 in eachline2:
eachline = eachline.replace(rep_word2,new_word2)
content2.append(eachline)
f_write = open(each_file,'w')
f_write.writelines(content1,cotent2)
f_write.close()
f_read.close()
a = '电子交易系统'
b = '大宗商品交易管理系统'
def read_file():
files = r'D:\我啊\新建文本文档.txt'#这是你的文件夹
f = open(files,'r',encoding = 'utf-8')
content = f.read()
for x in a: #遍历你想要old words
if x in content:
content = content.replace(a,b)#用新单词替换老单词
return content
f.close()
def write_file(xx):
file =r'D:\我啊\新建文本文档.txt' #同样是你的文件夹
c = open(file,'w',encoding = 'utf-8')
c.write(xx)
c.close()
def main():
aa = read_file()#返回一个改过的文本
write_file(aa)#然后覆盖写入你的文本内就可以了
main()
第二个单词也是同理,你可以吧遍历写一块
页:
[1]