Python學習筆記 Day11 檔案和異常

2021-09-02 23:13:03 字數 2323 閱讀 3642

逐行讀取

file_name =

"pi_digits.txt"

with

open

(file_name)

as file_object:

for line in file_object:

print

(line.rstrip(

))

使用檔案內容

file_name =

"pi_million_digits.txt"

with

open

(file_name)

as file_object:

lines = file_object.readlines(

) pi_string =

''for line in lines:

pi_string += line.rstrip(

)print

(pi_string)

print

(len

(pi_string)

)

寫入檔案
filename =

'programming.txt'

with

open

(filename,

'w')

as file_object:

file_object.write(

"i love programming!"

)

異常

try

: answer =

int(first_number)

/int

(second_number)

except zerodivisionerror:

print

("you can't divide bu 0!"

)else

:print

(answer)

分析文字
filename =

'alice.txt'

try:

with

open

(filename)

as f_obj:

contents = f_obj.read(

)except filenotfounderror:

msg =

"sorry, the file "

+ filename +

" does not exist."

print

(msg)

else

:#計算檔案大致包含多少個單詞

words = contents.split(

) num_words =

len(words)

print

("the file "

+ filename +

" has about "

+str

(num_words)

+" words."

)

同時處理多個檔案:將需要處理的檔名用列表儲存

#定義計算檔案有多少個單詞的函式

defcount_words

(filename)

:try

:with

open

(filename)

as f_obj:

contents = f_obj.read(

)except filenotfounderror:

msg =

"sorry, the file "

+ filename +

" does not exist."

print

(msg)

else

:#計算檔案大致包含多少個單詞

words = contents.split(

) num_words =

len(words)

print

("the file "

+ filename +

" has about "

+str

(num_words)

+" words."

)

filenames =

['alice.txt'

,'siddhartha.txt'

,'moby_dick.txt'

,'little_women.txt'

]for filename in filenames:

count_words(filename)

python 學習筆記 day11 裝飾器

現在有乙個需求,我們想計算一段程式執行的時間,可以採用time模組的time函式 def func print 哈哈哈哈 func 我們可以這樣做 import time deffunc start time.time 函式體內 執行開始的時間 time.sleep 0.02 因為這個程式太簡單,執...

機器學習學習筆記 day11

周志華 機器學習 學習筆記 最近開始學習機器學習,參考書籍西瓜書,做點筆記。第十一章 特徵選擇與稀疏學習 11.1 子集搜尋與評價 無關特徵 與訓練任務無關的特徵 冗餘特徵 包含的資訊能從其他特徵中推演出來 子集搜尋 前向 後向 雙向 子集評價 計算子集增益 資訊增益越大意味著特徵自己包含的有助於分...

Python廖雪峰教程學習筆記 Day11

養成乙個好的習慣只需要堅持21天,day11 這兩天主要學習一下物件導向的高階程式設計。使用 slots 由之前學習類的定義和例項的建立,我們可以給例項繫結不同的屬性,例如 class student object pass s student s.name tom 動態給例項繫結乙個屬性 prin...