python實(shí)現(xiàn)文件名批量替換和內(nèi)容替換
指定文件夾,指定文件類型,替換該文件夾下全部文件的內(nèi)容。
注意在window下的讀寫內(nèi)容需要指定編碼,還需要在文件頭指定#coding:utf-8 編碼,避免出現(xiàn)編碼問題。
#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
這個(gè)示例可以批量替換文件名和內(nèi)容
#!/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
相關(guān)文章
Python?Requests?基本使用及Requests與?urllib?區(qū)別
在使用Python爬蟲時(shí),需要模擬發(fā)起網(wǎng)絡(luò)請(qǐng)求,主要用到的庫有requests庫和python內(nèi)置的urllib庫,一般建議使用requests,它是對(duì)urllib的再次封裝,今天通過本文給大家講解Python?Requests使用及urllib區(qū)別,感興趣的朋友一起看看吧2022-11-11Python學(xué)習(xí)筆記之open()函數(shù)打開文件路徑報(bào)錯(cuò)問題
這篇文章主要介紹了Python學(xué)習(xí)筆記之open()函數(shù)打開文件路徑報(bào)錯(cuò)問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04Appium+python自動(dòng)化怎么查看程序所占端口號(hào)和IP
這篇文章主要介紹了Appium+python自動(dòng)化怎么查看程序所占端口號(hào)和IP,本文以FQ工具 Lantern 為例,通過圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下2019-06-06Python實(shí)現(xiàn)隨機(jī)生成一個(gè)漢字的方法分享
這篇文章主要為大家詳細(xì)介紹了Python如何實(shí)現(xiàn)隨機(jī)生成一個(gè)漢字的功能,文中的示例代碼講解詳細(xì),對(duì)我們深入了解Python有一定的幫助,需要的可以參考一下2023-01-01python數(shù)據(jù)分析之將爬取的數(shù)據(jù)保存為csv格式
Python內(nèi)置了CSV模塊,可直接通過該模塊實(shí)現(xiàn)csv文件的讀寫操作,在web應(yīng)用中導(dǎo)出數(shù)據(jù)是比較常見操作,下面這篇文章主要給大家介紹了關(guān)于python數(shù)據(jù)分析之將爬取的數(shù)據(jù)保存為csv格式的相關(guān)資料,需要的朋友可以參考下2022-06-06詳解DBSCAN算法原理及其Python實(shí)現(xiàn)
DBSCAN,即Density-Based Spatial Clustering of Applications with Noise,基于密度的噪聲應(yīng)用空間聚類,本文將詳細(xì)介紹DBSCAN算法的原理及其Python實(shí)現(xiàn),需要的可以參考下2023-12-12