python文字替換

2021-09-20 06:39:28 字數 622 閱讀 8285

def main():

import os

f_old = open('/home/pi/desktop/output.nc','r')

f_new = open('/home/pi/desktop/output_new.nc','w')

for line in f_old:

if 'g0 z#1' in line:

line = line.replace('g0 z#1','m5\ng4 p0.2')

elif 'g1 z#2' in line:

line = line.replace('g1 z#2','m3 s1000\ng4 p0.2')

f_new.write(line)

f_old.close()

f_new.close()

if __name__ == '__main__':

main()

讀取一行舊檔案,替換掉關鍵字,把g0 z#1』替換成』m5\ng4 p0.2』,『g1 z#2』替換成』m3 s1000\ng4 p0.2』,然後寫入新檔案。這樣一行一行的替換可以避免string占用記憶體過大,不過缺點是需要兩個檔案操作。

vim文字替換

一 基本模式 在命令模式下,可以實現快速替換文字,這在vim編輯過程中非常實用。基本的格式如下 range s pattern string c,e,g,i 開頭的冒號表示進入到命令模式,下面的介紹為了方便會省略這個符號 range 表示替換的範圍,以行為單位,比如 1,4 為從第一行到第四行,起始...

sed 文字替換

呼叫sed命令有兩種形式 sed options command file s sed options f scriptfile file s 刪除 d命令 sed 2d example 刪除example檔案的第二行。sed 2,d example 刪除example檔案的第二行到末尾所有行。se...

sed 文字替換

sed s front back aa.txt sed s front back aa.txt 這兩個命令的作用是一樣的 可以通過vi介面中操作 s front back g s front back 都是全域性替換 將檔案由檢視模式切換成命令模式 上面的 可以替換成 n 指定行數例如第一行 1s ...