Python學習(十二)文件操作和異常處理以及使用json存儲數據
Python 文件操作和異常處理
Python 文件操作
文件操作步驟
-
打開文件,打開方式(讀寫) open(file_name)
-
操作文件(增刪改查)
-
關閉文件, file_name.close()
三種基本的操作模式 r(只可讀) w(只可寫) a(追加) 流程: 1 創建文件對象 2 調用文件方法進行操作 3 關閉文件
讀文件
‘pi_digits.txt‘
3.1415926535
8979323846
2643383279
全文讀取
#需要讀取的文件
filename = ‘pi_digits.txt‘
#打開讀取文件
with open(filename) as file_object:
lines = file_object.read()
#尾行多一個空行
print(lines)
#刪除尾部的空行
print(lines.rstrip())
#操作完成關閉文件
filename.close()
3.1415926535
8979323846
2643383279
逐行讀取文件
#需要讀取的文件
filename = ‘pi_digits.txt‘
#打開讀取文件
with open(filename) as file_object:
#刪除行每行後面的空行
for line in file_object:
print(line.rstrip())
3.1415926535
8979323846
2643383279
創建一個包含文件各行內容的列表
#需要讀取的文件
filename = ‘pi_digits.txt‘
#創建一個變量
pi_sing = ‘‘
#打開讀取文件
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
#刪除行每行後面的空行
linea = line.rstrip()
#刪除行每行開頭的空行,並拼接到變量
pi_sing += line.strip()
print (pi_sing)
#統計變量長度
print (len(pi_sing))
print (‘====>>‘)
3.1415926535
12
====>>
3.14159265358979323846
22
====>>
3.141592653589793238462643383279
32
====>>
百萬位的圓周率中搜索是否包含你的生日
#pi_million_digits.txt 百萬位的圓周率表
#需要讀取的文件
filename = ‘pi_million_digits.txt‘
#打開讀取文件
with open(filename) as file_object:
lines = file_object.readlines()
#創建一個變量
pi_string = ‘‘
for line in lines:
#刪除行每行開頭的空行,並拼接到變量
pi_string += line.strip()
#輸入一個變量
birthday = input("Enter your birthday, in the form mmddyy: ")
#if判斷是否純在內容中
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")
Enter your birthday, in the form mmddyy: 11111111111111111111111111
Your birthday does not appear in the first million digits of pi.
寫文件
寫入操作方式:
r:讀取文件
w:清空寫入文件
a:追加寫入文件
r+:文件讀寫模式
寫入空文件
#打開空文件並寫入內容
with open(filename, ‘w‘) as file_object:
file_object.write(‘\nI Love programming!‘)
I Love programming!
追加寫入多行內容
##打開空文件並寫入內容
with open(filename, ‘a‘) as file_object:
#每行添加換行符
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
I Love programming!
I also love finding meaning in large datasets.
I love creating apps that can run in a browser.
註意:寫入多行時註意使用換行符 “\n” 文件打開後光標默認停在文件最後一個字符位
Python 異常處理
-
Python 異常處理:指程序執行過程中各種原因造成的程序中斷或掛死。
-
python中使用try_except模塊來處理這些意外情況,try_except模塊讓程序執行指定的操作,同時反饋python發生了什麽錯誤。
-
使用try_except模塊即便異常發生也不會退出程序而是會繼續運行,顯示你編寫的友好錯誤消息。
處理異常
處理流程:
- 獲取異常信息類型
- 將異常類型添加到try_except模塊中判斷,避免程序崩潰。
try_except模塊的使用使錯誤頁面更友好
異常信息類型獲取
#代碼
print (5/0)
#報錯
print (5/0)
ZeroDivisionError: division by zero
報錯類型:ZeroDivisionError
將異常類型添加到try_except模塊中判斷
try:
print (5/0)
except ZeroDivisionError:
print ("You can‘t divide by zero")
程序正常執行友好提示錯誤
You can‘t divide by zero
try_except模塊中else代碼塊
需要在tty代碼塊中執行成功的代碼,在繼續運行的需要通過else代碼塊告訴程序。
tty:判斷代碼是否會引發錯誤
except:將錯誤信息告訴程序
else:將校驗後的代碼,交由程序運行
代碼實例一:
判斷是否是輸入的整數
判斷是否整數除以“0”
python中不允許一個數字除以“0”
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("Second number: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can‘t divide by 0!")
#可以使用多個except提示錯誤類型
except ValueError:
print("You can‘tinvalid literal for int()!")
else:
print(answer)
Give me two numbers, and I‘ll divide them.
Enter ‘q‘ to quit.
First number: 5
Second number: 2
2.5
First number: 0
Second number: 0
You can‘t divide by 0!
First number: 0.8
Second number: 0
You can‘tinvalid literal for int()!
代碼實例二:
判斷文件是否存在
#文件名稱
filename = ‘alice.txt‘
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError as e:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
Sorry, the file alice.txt does not exist.
代碼實例三:
判斷文件是否存在
分析存在的文件中包含了大致多少個單詞
def count_words(filename):
"""Count the approximate number of words in a file.分析存在的文件中包含了大致多少個單詞"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# Count approximate number of words in the file.
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)
The file alice.txt has about 29461 words.
The file siddhartha.txt has about 42172 words.
The file little_women.txt has about 189079 words.
使用json存儲數據
模塊json能夠將簡單的python數據結構轉存到文件中,並在程序再次運行時加載該文件中的數據,也可以使用json在python程序之間分享數據。
json數據格式並非python專用
json模塊的讀寫功能
json.dump() 存儲數據 json.load() 讀取數據
json模塊的寫功能
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = ‘numbers.json‘
with open(filename, ‘w‘) as file_object:
json.dump(numbers, file_object)
列表numbers被寫入numbers.json文件中
[2, 3, 5, 7, 11, 13]
json模塊的讀功能
import json
filename = ‘numbers.json‘
with open(filename) as file_object:
numbers = json.load(file_object)
print(numbers)
讀出umbers.json文件中的信息
[2, 3, 5, 7, 11, 13]
使用json保存和讀取用戶生成的數據和重構
用戶生成數據如果不以某種方式保存,當程序停止時會出現數據信息丟失現象。json模塊很好的解決了這個問題。
import json
def get_stored_username():
"""Get stored username if available.
如果存儲了用戶名,就獲取他"""
filename = ‘username.json‘
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""Prompt for a new username.
提示輸入用戶名"""
username = input("What is your name? ")
filename = ‘username.json‘
with open(filename, ‘w‘) as f_obj:
json.dump(username, f_obj)
return username
def greet_user():
"""Greet the user by name.
問候用戶並指出用戶名"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We‘ll remember you when you come back, " + username + "!")
greet_user()
首次執行代碼:
What is your name? yunlei
We‘ll remember you when you come back, yunlei!
再次執行代碼:
Welcome back, yunlei!
Python學習(十二)文件操作和異常處理以及使用json存儲數據