1. 程式人生 > >Python學習3月8號【python編程 從入門到實踐】---》筆記(1)

Python學習3月8號【python編程 從入門到實踐】---》筆記(1)

store 執行 \n true r.js under 進行 一聲 tor

第十章:處理文件和異常


#學習處理文件,讓程序能夠快速地分析大量的數據
#學習錯誤處理,避免程序在面對意外情形時崩潰
#學習異常,是python創建的特殊對象,用於管理程序運行時出現
#學習模塊json,它讓你能夠保存用戶數據,以免在程序停止運行後丟失

10.1 從文件中讀取數據

#10.1.1 讀取整個文件



#10.1.3 逐行讀取
##調用For循環
# filename= ‘pi_digits.txt‘
# with open (filename) as file_object:#使用了關鍵字with,讓python負責妥善地打開和關閉文件。
# for line in file_object:#為查看文件的內容,我們通過對文件對象執行循環來遍歷文件中的每一行

# print(line.rstrip())

#10.1.4 創建一個包含文件各行內容的列表
# filename = ‘pi_digits.txt‘
# with open(filename) as file_object:
# lines = file_object.readlines()
# for line in lines:
# print(line.rstrip())


#10.2.1寫入空文件
 
filename = ‘programming.txt‘

with open (filename,"w") as file_object:
file_object.write(" I love programming.")


#10.2.3附加到文件

#以‘a‘的附加模式打開,寫入到文件的行都將添加到文件末尾
filename = ‘programming.txt‘

with open (filename,"a") as file_object:
file_object.write(" also love finding meaning in large datasets.\n")
file_object.write(" i love creating apps that can run in a browser.\n")



#10.3 異常


#10.3.1 處理ZeroDivisionError異常


# try:
# print(5/0)
# except ZeroDivisionError:
# print(" You can‘t divide by zero ")

10.3.3 使用異常避免崩潰
#try-except-else代碼塊的工作原理大致如下:

#處理FileNotFoundError 異常


#可以使用try-except 代碼塊以直觀的方式進行處理。

filename= ‘alice.txt‘
try:
with open(filename) as f_obj:## 會由幾率發生異常的運行
contens = f_obj.read()##將read()得到的內容放進contens裏面
except FileNotFoundError:#如果發生FileNotFoundError異常就執行一下行代碼
msg="Sorry , the file " + filename + " does not exist."
print(msg)##輸出一個提醒代碼

10.3.4 else代碼塊
#try-except-else代碼塊的工作原理大致如下:

print("Give me two numbers , and i‘ll divide them .")
print("Enter ‘q‘ to quit .")

while True:
first_number=input("\nFirst number: ")
if first_number==‘q‘:
break
second_number=input("\nSecond number: ")
try: ###### try-except-else代碼塊的工作原理,python嘗試執行try代碼塊中的代碼;
        answer = int(first_number) / int(second_number)###有可能發生異常的一行代碼
except ZeroDivisionError:            #except代碼塊告訴python,出現ZeroDivisionError異常時該怎麽辦,下一行就是異常後執行的代碼塊。

print("You can‘t divide by 0!")
else:                       ####只有可能引發異常的代碼才需要放在try語句中;有一些僅在try代碼塊成功執行時才需要運行的代碼,並且放在else語句裏面
        print(answer)



10.3.6分析文本

#以空格為分隔符將字符串將字符串分拆成多個部分,並將這些部分都存儲到一個列表中
# title = "Alice in Wonderland "
# a=title.split()#它時根據一個字符串創建一個單詞列表。
# print(a)


10.3.7 使用多個文件
def count_words(filename):
"計算一個文件大致有多少個單詞"
try:
with open (filname) as f_obj:
contents= f_obj.read()
except FileExistsError: # 如果想在失敗時候一聲不吭,可以在except代碼塊中明確什麽都不做,可以寫入pass代碼
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")

filename = [‘alice.text‘,‘siddhartha.txt‘,‘moby_dick.txt‘]
for filename in filenames:
  count_words(filename)

在以上代碼可知,使用try-except代碼塊提供了兩個重要的優點:避免讓用戶看到traceback;讓程序能夠分析能夠找到的其他文件。


10.4存儲數據


#模塊json讓你能夠將簡單的python數據結構轉儲到文件中,並在程序再次運行時加載該文件中的數據。
#json 格式最初是為(JavaScriptObject Notation) 格式最初是為Javascript開發。

 
 
import json
numbers=[2,3,4,56,15]

filename = ‘number.json‘ ##使用文件擴展名。json來指出文件存儲的數據為JSON格式。
with open(filename,‘w‘)as f_obj:
json.dump(numbers,f_obj)      ##函數json.dump()接受兩個實參:要存儲的數據以及可用於存儲數據的文件對象。
print(numbers)

兩個使用了兩個不同函數,一個是load一個dump 。

import json
filename = ‘number.json‘
with open(filename) as f_obj:
numbers=json.load(f_obj)      ##我們使用函數json.load()加載存儲在numbers.json中的信息,並將其存儲到變量numbers中。

print(numbers)


 
import json

def get_stored_username():
##如果存儲了用戶名,就獲取它
filename = ‘username.json‘
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
#問候用戶,並指出其名字
username= get_stored_username()
if username:
print("Welcome back," + username + "!")
else:
username = input("What is your name ?")
filename =‘username.json‘
with open(filename,‘w‘)as f_obj:
json.dump(username,f_obj)
print("We‘ll remember you when you come back," + username + "!")

greet_user()





























































Python學習3月8號【python編程 從入門到實踐】---》筆記(1)