1. 程式人生 > 實用技巧 >第十章檔案和異常

第十章檔案和異常

#讀取檔案操作,
# 當前路徑
with open('pi.txt') as file:
print(file.read())
# 絕對路徑
with open('D:\db.txt') as file:
print(file.read())

# 這樣執行打出來的會多一行空白,是因為每個末尾都有一個換行符
filename='pi.txt'
with open(filename) as file:
for line in file:
print(line)
#讓圓周率連在一起
filename="pi.txt"
with open(filename) as file:
lines=file.readlines()
p_string=''
for line in lines:
p_string+=line.strip()
print(p_string)
print(len(p_string))

#圓周率有你的生日沒有
filename="pi.txt"
with open(filename) as file:
lines=file.readlines()
p=''
for line in lines:
p+=line.rstrip()
birthday=input("Enter you birthday:")
if birthday in p:
print("Your birthday appears in the first million digits of pi")
else:
print("not apperas ")

#總結:readLine 從字面意思可以看出,該方法每次讀出一行內容,所以,讀取時佔用記憶體小,比較適合大檔案,該方法返回一個字串物件。,ReadLines 一起性讀取文中所有的行數,並按行返回到list,方便我們遍歷
read() : 一次性讀取整個檔案內容。推薦使用read(size)方法,size越大執行時間越長


# 寫入檔案操作
# 指定開啟檔案時,讀取模式r,寫入模式w,附加模式a,讓你能讀取和寫入檔案的模式r+,如果是省略模式
#則預設只讀,如果寫入檔案不存在,會自動建立,用w時候要小心,如果存在了,會返回物件前清空該檔案
filename="li.txt"
with open(filename,'w') as file:
file.write("I love programming.\n")
file.write("I love programming.\n")
#追加模式a
filename="li.txt"
with open(filename,'a') as file:
file.write("I love dataing.\n")
file.write("I love swiming.\n")



#異常,如果Try 中的沒有問題,那麼就輸出try 中的內容,如果有問題,就輸出except
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")

#else 程式碼塊, 依賴於try 執行成功後的程式碼塊都要放在else 程式碼塊中
print("Give me two number, I will divide it")
while True:
first_number=input("\n First number:")
if first_number=='q':
break
second_number=input("\n second number:")
try:
answer=int(first_number)/int(second_number)
except ZeroDivisionError:
print("You can't divie by 0")
else:
print(answer)
#檔案異常 FileNotFoundError
filename='hell.txt'
try:
with open(filename) as file:
contents= file.read()
except FileNotFoundError:
msg="Sorry,the file "+filename+" not exist"
print(msg)


# 統計文字有多少個單詞,這些檔案可能不存在
def count_words(filename):
try:
with open(filename) as file:
contents=file.read()
except FileNotFoundError:
msg="sorry,the file not exist"
print(msg)
else:
word=contents.split()
numwords=len(word)
print(filename+" has about "+str(numwords))
filename=['alice.txt','li.txt','pi.txt']
for f in filename:
count_words(f)



#失敗時一聲不吭,pass 這個表示直接略過,pass 就是不做任何操作
def count_words(filename):
try:
with open(filename) as file:
contents=file.read()
except FileNotFoundError:
pass
else:
word=contents.split()
numwords=len(word)
print(filename+" has about "+str(numwords))
filename=['alice.txt','li.txt','pi.txt']
for f in filename:
count_words(f)


還有json操作,但是我認為書上說的淺。回頭補資料