# -*- coding: utf-8 -*-
"""
Created on Fri Feb 17 20:25:05 2017
@author: who
"""
import os
import os.path
import re
import string
rootdir=r'D:\test'
for parent, dirnames, filenames in os.walk(rootdir): # 三個參數:分別返回1.父目錄 2.所有文件夾名字(不含路徑) 3.所有文件名字
try:
for filename in filenames:
filenamepre=os.path.splitext(filename.decode("gbk"))[0];#文件名前綴
filetype=os.path.splitext(filename.decode("gbk"))[1].lower();#文件擴展名
pswpath = os.path.join(parent, filename.decode("gbk"));
tmppath = os.path.join(r'D:\testxx',filename.decode("gbk")) #寫到另一個文件夾#
if filetype=='.txt':
a=string.find(filenamepre,'9999') ####符合類型的文件####
if a==0:
tmp_file = open(tmppath, "w")
with open(pswpath) as f:
lines = f.readlines()
for line in lines: ####一行一行讀取 ####
if line.find('aaa') > -1: ####找到含aaa有的這行,匹配出對應整數數字####
m=re.compile('aaa([0-9]+)')
ms=m.search(line)
print ms.group(1)
line.replace(ms.group(1),filenamepre) ####進行替換
tmp_file.write(line.replace(ms.group(1),filenamepre)) ###寫出替換的該行
else:
tmp_file.write(line)
tmp_file.close()
else:
tmp_file = open(tmppath, "w")
with open(pswpath) as f:
lines = f.readlines()
for line in lines: ####一行一行讀取 ####
tmp_file.write(line)
tmp_file.close()
except IOError:
pass