Python學習 第十七天

2021-08-13 08:02:24 字數 2268 閱讀 2638

在下這廂有禮了 練習

python修改檔案時,使用w模式會將原本的檔案清空/覆蓋。可以先用讀(r)的方式開啟,寫到記憶體中,然後再用寫(w)的方式開啟。

yesterday when i was young

昨日當我年少輕狂

the taste of life was sweet

生命的滋味是甜的

as rain upon my tongue

#將檔案讀取到記憶體中

with open("./fileread.txt","r",encoding="utf-8") as f:

lines = f.readlines()

#寫的方式開啟檔案

with open("./fileread.txt","w",encoding="utf-8") as f_w:

for line in lines:

if "taste" in line:

#替換line = line.replace("taste","tasting")

f_w.write(line)

2.全文中搜尋替換或者單行替換

#文字內容

yesterday when i was young

昨日當我年少輕狂

the taste of life was sweet

生命的滋味是甜的

as rain upon my tongue

taste

taste

taste

taste

#定義乙個函式,帶有4個引數

#x 表示要更新的檔名稱

#y 表示要被替換的內容

#z 表示 替換後的內容

#s 預設引數為 1 表示只替換第乙個匹配到的字串

# 如果引數為 s = 'g' 則表示全文替換

def string_switch(x,y,z,s=1):

with open(x, "r", encoding="utf-8") as f:

#readlines以列表的形式將檔案讀出

lines = f.readlines()

with open(x, "w", encoding="utf-8") as f_w:

#定義乙個數字,用來記錄在讀取檔案時在列表中的位置

n = 0

#預設選項,只替換第一次匹配到的行中的字串

if s == 1:

for line in lines:

if y in line:

line = line.replace(y,z)

f_w.write(line)

n += 1

break

f_w.write(line)

n += 1

#將剩餘的文字內容繼續輸出

for i in range(n,len(lines)):

f_w.write(lines[i])

#全域性匹配替換

elif s == 'g':

for line in lines:

if y in line:

line = line.replace(y,z)

f_w.write(line)

測試1)預設引數 1,只替換匹配到的第一行

string_switch("fileread.txt","taste","tasting")

#結果yesterday when i was young

昨日當我年少輕狂

the tasting of life was sweet

生命的滋味是甜的

as rain upon my tongue

taste

taste

taste

taste

2)全域性替換

string_switch("fileread.txt","taste","tasting","g")

#結果yesterday when i was young

昨日當我年少輕狂

the tasting of life was sweet

生命的滋味是甜的

as rain upon my tongue

tasting

tasting

tasting

tasting

學習python的第十七天

書中寫道 現在你應該有能力寫更有趣的程式出來了。如果你能一直跟得上,你應該已經看出將 if語句 和 布林表達 結合起來可以讓程式作出一些智慧型化的事情。是時候停下學習新知的步伐,開始複習之前學習過的知識,雖然有些部分比較簡單,有些部分還是不容易理解。這節學習for loop for迴圈 建立各種各樣...

linux學習第十七天

18.1 資料庫管理系統 資料庫是指按照某些特定結構來儲存資料資料的資料倉儲。在當今這個大資料技術迅速崛起的年代,網際網路上每天都會生成海量的資料資訊,資料庫技術也從最初只能儲存簡單的 資料的單一集中儲存模式,發展到了現如今儲存海量資料的大型分布式模式。在資訊化社會中,能夠充分有效地管理和利用各種資...

打卡第十七天

第二次了,又沒過.有時候會有一種失敗感,這幾年好像什麼都沒做好,過的好像也不是很開心。昨天兵查過成績後心情就低落起來了,尤其是聽到晨晨得知她沒過時發出的驚訝聲音 你竟然沒過?時,心情立馬跌到了谷底,回到宿舍就再也繃不住了,大哭了一場,媽媽打 詢問情況,看到女兒哭的傷心,竟也無措起來,不知如何安慰。於...