python3 資料夾下所有檔案 字串替換

2021-10-25 07:18:32 字數 1412 閱讀 4219

替換資料夾下所有檔案中的字串。

#coding=utf8

from os import chdir, getcwd, listdir, path

import codecs

import re

def excuepath(folder_path, blacklist, extends):

chdir(folder_path)

cwd=getcwd()

dirs=listdir(cwd)

for tmp in dirs:

# 排除blacklist資料夾

if tmp not in blacklist:

fpath=path.join(cwd, tmp)

if path.isfile(fpath):

print('fpath=',fpath)

# 只extends的檔案型別

if fpath.split('.')[-1] in extends:

data = ""

with codecs.open(fpath, "r", "utf-8") as rfile:

data = rfile.read()

with codecs.open(fpath, "w", "utf-8") as wfile:

replace_times = 0

replace_times += data.count(item[0])

data = data.replace(item[0], item[1]);

print(r'替換次數:', replace_times)

print()

wfile.write(data)

#如果是資料夾,遞迴

elif path.isdir(fpath):

excuepath(fpath)

def load_replace_keys(key_path):

with codecs.open(key_path, "r", "utf-8") as rfile:

for item in rfile.readlines():

if __name__=='__main__':

# 替換的鍵值對,一行兩個字串,前面的是舊字串,後面的是新字串,中間用空格隔開

key_path = './replace.keys.txt'

# 待替換檔案的 資料夾目錄,會遞迴檢索檔案,並替換檔案中所有的字串

# 只匹配下面的檔案型別

extends = ['ftl', 'js']

# 排除哪些資料夾

blacklist = ['.history', 'dest', 'libs']

excuepath(folder_path, blacklist, extends)

python 3讀取檔案 Python3 檔案讀寫

python open 方法用於開啟乙個檔案,並返回檔案物件,在對檔案進行處理過程都需要使用到這個函式 1.讀取檔案 with open test json dumps.txt mode r encoding utf 8 as f seek 移動游標至指定位置 f.seek 0 read 讀取整個檔...

Python 提取資料夾下所有檔案

tensorflow版faster rcnn 訓練自己的資料集 需要提取名稱構成訓練集 train.txt 測試集 val.txt 驗證集 time 2018 12 29 10 50 author moli99 coding utf 8 import os def file name file di...

Python遍歷資料夾下所有檔案

7只遍歷當前資料夾 不遞迴遍歷 import glob dir test samples glob.glob dir print samples print len samples test 1.txt test new 2遍歷當前資料夾下所有的.txt import glob dir test s...