python實現文件名批量替換和內容替換
指定文件夾,指定文件類型,替換該文件夾下全部文件的內容。
注意在window下的讀寫內容需要指定編碼,還需要在文件頭指定#coding:utf-8 編碼,避免出現編碼問題。
#coding:utf-8
import os
import os.path
path='.'
oldStr='.php'
newStr='.html'
for (dirpath, dirnames, filenames) in os.walk(path):
for file in filenames:
if os.path.splitext(file)[1]=='.html':
print(file)
filepath=os.path.join(dirpath,file)
try:
text_file = open(filepath, "r")
lines = text_file.readlines()
text_file.close()
output = open(filepath,'w',encoding= 'utf-8')
for line in lines:
#print(line)
if not line:
break
if(oldStr in line):
tmp = line.split(oldStr)
temp = tmp[0] + newStr + tmp[1]
output.write(temp)
else:
output.write(line)
output.close()
except Exception:
print(Exception)
break
這個示例可以批量替換文件名和內容
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, re
def multi_replace(text, adict):
rx = re.compile('|'.join(map(re.escape, adict)))
def xlat(match):
return adict[match.group(0)]
return rx.sub(xlat, text)
def batrename(curdir, pairs):
for fn in os.listdir(curdir):
newfn = multi_replace(fn, pairs)
if newfn != fn:
print("Renames %s to %s in %s." % (fn, newfn, curdir))
os.rename(os.path.join(curdir, fn), os.path.join(curdir, newfn))
file = os.path.join(curdir, newfn)
if os.path.isdir(file):
batrename(file, pairs)
continue
text = open(file).read()
newtext = multi_replace(text, pairs)
if newtext != text:
print("Renames %s." % (file,))
open(file, 'w').write(newtext)
if __name__=="__main__":
while True:
oldname = raw_input("Old name: ")
newname = raw_input("New name: ")
if oldname and newname:
batrename(os.path.abspath('.'), {oldname:newname})
else: break
相關文章
Python lambda和Python def區(qū)別分析
Python支持一種有趣的語法,它允許你快速定義單行的最小函數。這些叫做lambda的函數,是從Lisp借用來的,可以用在任何需要函數的地方2014-11-11
淺談numpy中l(wèi)inspace的用法 (等差數列創(chuàng)建函數)
下面小編就為大家?guī)硪黄獪\談numpy中l(wèi)inspace的用法 (等差數列創(chuàng)建函數)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06

