day11 檔案和異常

2021-10-03 14:19:30 字數 3834 閱讀 3118

#讀寫文字檔案

defmain()

: f =

open

("twoone.txt"

,"r"

,encoding=

"utf-8"

)print

(f.read())

f.close

main(

)

#讀寫文字檔案,異常處理

defmain()

: f =

none

try:

f =open

("twoone.txt"

,"r"

,encoding=

"utf-8"

)print

(f.read())

except filenotfounderror:

print

("無法開啟指定的檔案!"

)except lookuperror:

print

("指定了未知的編碼!"

)except unicodedecodeerror:

print

("讀取檔案時解碼錯誤!"

)finally

:if f:

f.close(

)if __name__ ==

"__main__"

: main(

)

import time 

defmain()

:#一次性讀取整個檔案的內容

with

open

("twoone.txt"

,"r"

,encoding=

"utf-8"

)as f:

print

(f.read())

#通過for-in 迴圈逐行讀取

with

open

("twoone.txt"

,mode =

"r")

as f:

for line in f :

print

(line ,end=

" ")

time.sleep(

0.5)

print()

#讀取檔案按行讀取到列表中

with

open

("twoone.txt"

)as f :

print

(line)

if __name__ ==

"__main__"

: main(

)

from math import sqrt 

defis_prime

(n):

assert n >

0for factor in

range(2

,int

(sqrt(n)+1

)):if n%factor ==0:

return

false

return

true

if n!=

1else

false

defmain()

: filenames =

("a.txt"

,"b.txt"

,"c.txt"

) fs_list =

try:

for filename in filenames:

open

(filename,

"w",encoding =

"utf-8"))

for number in

range(1

,10000):

if is_prime(number)

:if number<

100:

fs_list[0]

.write(

str(number)

+"\n"

)elif number<

1000

: fs_list[1]

.write(

str(number)

+"\n"

)else

: fs_list[2]

.write(

str(number)

+"\n"

)except ioerror as ex :

print

(ex)

print

("寫檔案時發生錯誤"

)finally

:for fs in fs_list:

fs.close(

)print

("操作完成"

)if __name__ ==

"__main__"

: main(

)

#讀寫二進位制檔案

defmain()

:try

:with

open

("ball.png"

,"rb"

)as fs1:

data =fs1.read(

)print

(type

(data)

)with

open

("ball_game.png"

,"wb"

)as fs2:

fs2.write(data)

except filenotfounderror as e:

print

("指定的檔案無法開啟"

)except ioerror as e:

print

("讀寫檔案出現錯誤"

)print

("程式執行結束"

)if __name__ ==

"__main__"

: main(

)

#儲存jaon檔案

import json

defmain()

: mydict =,,

]}try:

with

open

("data.json"

,"w"

,encoding=

"utf-8"

)as fs:

json.dump(mydict,fs)

except ioerror as e :

print

(e)print

("儲存資料完成!"

)if __name__ ==

"__main__"

: main(

)

———————————————————————————————————————————
#讀寫json檔案

import requests

import json

defmain()

: resp =requests.get(

"") data_model =json.loads(resp.text)

for news in data_model[

'newslist']:

print

(news[

"title"])

if __name__ ==

"__main__"

: main()""

有錯誤,待完善,還沒搞定,搞懂

""

Python學習筆記 Day11 檔案和異常

逐行讀取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 o...

基礎DAY11 異常丟擲及捕獲

完整的異常語法try 提示使用者輸入乙個整數 num int input 請輸入乙個整數 使用 8 除以使用者輸入的整數並且輸出 result 8 num print result except valueerror 針對錯誤型別1,對應的 處理 print 不是整數 except exceptio...

1 1 檔案許可權

站點目錄和檔案許可權 myproject index.php 結論 所有的許可權都是給予apache的許可權 其他人 而不是使用者和使用者組,因為是www data使用者執行所有的操作。之所以給使用者和使用者組設定合適的全下是方便開發人員檢視,編輯 而已 1 最小許可權 myproject apac...