Python學習(8) 替換檔案內容

2021-10-09 22:19:34 字數 2897 閱讀 2106

在前處理時替換檔案裡不被翻譯工具識別的內容。用 python 寫完指令碼後,實現 perl 指令碼呼叫 python 指令碼並執行。

delete-content-2.7.py

# -*- coding:utf-8 -*-

import os

import re

import io

import sys

str1 =

print sys.ar**[1]

source_path = sys.ar**[1]

+"enu\\setupres\\locale\\en-us\\"

#source_path = "c:\\temp\\enu\\setupres\\locale\\en-us\\"

for root1, dirs, files1 in os.walk(source_path)

:#print(root1)

#獲取檔名列表

for i in

range

(len

(files1)):

filename_source = files1[i]

fa = io.

open

(root1 + filename_source,

'r+'

, encoding=

'utf-8'

) a1 = re.sub(r' &&.*&&',""

, fa.read())

#print(a1)

fb = io.

open

(root1 + filename_source,

'w+'

, encoding=

'utf-8'

) fb.write(a1)

beforeupdateproject.pl

#!/usr/bin/env perl

use warnings;

use strict;

our$mylocation

;$mylocation

="c:\\temp\\"

;#logmessage("plugin beforeupdateproject.pl is called.");

my$rv

= system(

"$mylocation\\plugin\\delete-content-2.7.py $mylocation");

print

"exit: $rv\n"

後處理時,要把之前的內容再加到翻譯檔案及原始檔中,同樣用perl呼叫執行 python指令碼。

add-content-2.7.py

# -*- coding:utf-8 -*-

import os

import re

import io

import sys

filter=[

".xml"

]#設定過濾後的檔案型別 當然可以設定多個型別

defall_path

(dirname)

: result =

#所有的檔案

for root,

dir, files in os.walk(dirnfileame)

:# root #當前主目錄

# dir #當前主目錄下的所有目錄

# files #當前主目錄下的所有檔案

for filename in files:

apath = os.path.join(

dir, filename)

#合併成乙個完整路徑

ext = os.path.splitext(apath)[1

]# 獲取檔案字尾 [0]獲取的是除了檔名以外的內容

if ext in

filter

:return result

#print(all_path("c:\\temp\\"))

#執行結果

print sys.ar**[1]

xml_path = all_path(sys.ar**[1]

)#print(xml_path)

for i in

range

(len

(xml_path)):

#print(xml_path[i])

fa = io.

open

(xml_path[i]

,'r+'

, encoding=

'utf-8'

)#print(fa)

a1 = re.sub(r'***x'

,'***x &&yearrelease&&'

, fa.read())

#print(a1)

fb = io.

open

(xml_path[i]

,'w+'

, encoding=

'utf-8'

) fb.write(a1)

aftergenerateproject.pl

#!/usr/bin/env perl

use warnings;

use strict;

our$mylocation

;$mylocation

="c:\\temp\\"

;#logmessage("plugin beforeupdateproject.pl is called.");

my$rv

= system(

"$mylocation\\plugin\\add-content-2.7.py $mylocation");

print

"exit: $rv\n"

替換檔案內容

前幾天無意間看見一道題,內容大致是這樣的。有乙個檔案,裡面內容是這樣的格式 1 aa 2 bb 3 cc 4 dd 現在想插入3 ee,如果存在3 那麼把後面內容換成新內容,如果不存在則新增一行。一開始我是這麼寫的 後來經指點使用字典可以這麼寫 tmp with open 1 r as fd a f...

python 練習 替換檔案內容

1.替換 import re file name new 4.txt fp open file name,r alllines fp.readlines fp.close fp open file name,w for eachline in alllines a re.sub 0.0.0.0 1....

使用python替換檔案內容

最新學習python使用到的替換檔案文字的操作。傳入檔案 file 將舊內容 old content 替換為新內容 new content defreplace file old content,new content content read file file content content.r...