国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現文件名批量替換和內容替換

2020-02-23 05:14:00
字體:
來源:轉載
供稿:網友

指定文件夾,指定文件類型,替換該文件夾下全部文件的內容。

注意在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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 福州市| 周宁县| 天水市| 砀山县| 淮阳县| 太湖县| 纳雍县| 亚东县| 彩票| 定兴县| 康定县| 丽江市| 犍为县| 巴东县| 呼玛县| 白河县| 五莲县| 彭水| 焦作市| 墨竹工卡县| 达尔| 大庆市| 迭部县| 庆云县| 宜兴市| 博兴县| 伊金霍洛旗| 都江堰市| 镇原县| 西乡县| 天水市| 紫阳县| 纳雍县| 鹿邑县| 延寿县| 济阳县| 定结县| 宁陕县| 清水县| 广饶县| 建宁县|