欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 讀取文件并替換字段的實例

 更新時間:2018年07月12日 09:18:52   作者:烏鴉來襲  
今天小編就為大家分享一篇python 讀取文件并替換字段的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

如下所示:

fp = open(''test2.txt','w') #打開你要寫得文件test2.txt
lines = open('test1.txt').readlines() #打開文件,讀入每一行
for s in lines:
fp.write( s.replace('love','hate').replace('yes','no'))  # replace是替換,write是寫入
fp.close() # 關(guān)閉文件
import os
import re

f_path = r'c:\a.txt'
f = open (f_path, "r+")
open('c:\\test.txt', 'w').write(re.sub(r'hello world', 'Love python', f.read()))

原文:

參考備忘,指針這個沒明白什么意思,找時間驗證下

#寫在原文件中
fp3=open("file3.txt","r+") #不用w w會清空數(shù)據(jù)
s=fp3.read()#讀出 
fp3.seek(0,0) #指針移到頭 原來的數(shù)據(jù)還在是替換 會存在一個問題 如果少  會替換不了全部數(shù)據(jù),自已思考解決!
#從頭寫入
fp3.write(s.replace("hello","good"))
fp3.close()
import os
os.chdir('D:\\')    # 跳到D盤
if not os.path.exists('test1.txt'): # 看一下這個文件是否存在
exit(-1)             #不存在就退出
lines = open('test1.txt').readlines() #打開文件,讀入每一行
fp = open(''test2.txt','w') #打開你要寫得文件test2.txt
for s in lines:
# replace是替換,write是寫入
fp.write( s.replace('love','hate').replace('yes','no'))  
fp.close() # 關(guān)閉文件

以上這篇python 讀取文件并替換字段的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論