1. 程式人生 > >【Python學習記錄——從入門到放棄】九、檔案與異常

【Python學習記錄——從入門到放棄】九、檔案與異常

本文使用的書籍是《Python程式設計:從入門到實踐》
本文使用的是Python3.6
一、從檔案中讀取資料
這一節主要講的是如何讀取檔案,無非就是幾個方法而已。

  1. 讀取整個檔案
    首先建立一個檔案
3.1415926335
8979323846
2643383279

儲存在pi_digits.txt
接下來我們用程式開啟並讀取這個檔案

with open('pi_digits.txt') as file_object:
	contents = file_object.read()
	print(contents)

注意,程式和pi_digits.txt要放在同一目錄下。
根據程式輸出的結果,發現輸出末尾多了一個空行,我們要使用rstrip()來刪除多出來的空行。

with open('pi_digits.txt') as file_object:
	contents = file_object.read()
	print(contents.rstrip())
  1. 檔案路徑
    當你需要讀取放在資料夾的檔案的時候,就要把路徑放在open裡
    windows記得是用
    Linux和OS X使用/
    with open(‘路徑\檔名’) as file_object

  2. 逐行讀取

with open('pi_digits.txt') as file_object:
    for line in file_object:
        print
(line.rstrip())
  1. 建立一個包含檔案各行內容的列表
filename = 'pi_digits.txt'

with open(filename) as file_object:
	lines = file_object.readlines()

for line in lines:
	print(line.rstrip())
  1. 使用檔案的內容
filename = 'pi_30_digits.txt'

with open(filename) as file_object:
	lines = file_object.readlines(
) pi_string = '' for line in lines: pi_string += line.strip() print(pi_string) print(len(pi_string))

這樣,我們就得到了檔案中的資料了。

  1. 包含一百萬位的大型檔案
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()

print(pi_string[:52] + "...")
print(len(pi_string))

這個跟上面的操作差不多,沒有什麼不同,就是所用資料更大而已。

  1. 圓周率值中包含你的生日嗎
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 birthday in pi_string:
	print("Your birthday appears in the first million digit of pi!")
else:
	print("Your birthday does not appear in the first million digits of pi.")")

動手試一試:

# 10-1
filename = 'learning_python.txt'
with open(filename) as file_object:
	print('第一種:')
	print(file_object.read().rstrip())

with open(filename) as file_object:
	print('第二種:')
	for line in file_object:
		print(line.rstrip())

with open(filename) as file_object:
	lines = file_object.readlines()

print("第三種:")
for line in lines:
	print(line.rstrip())

# learning_python.txt
In python you can print.
In python you can input.
In python you can make a list.
# 10-2
with open(filename) as file_object:
	lines = file_object.readlines()

for line in lines:
	print(line.replace('python', 'Java').rstrip())

二、寫入檔案
這一節主要講的是寫檔案,跟讀檔案差不多233。

  1. 寫入空檔案
filename = 'programming.txt'

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

注意:現在open()裡除了檔名,還有另一個引數’w’,這個引數代表的是寫入模式。
除此之外,還有其他模式:

引數 模式
w 寫入模式
r 讀取模式
a 附加模式
r+ 讀取和寫入模式

【重點注意!!!注意!!注意了!】
如果你使用’w’寫入模式的時候,在開啟檔案時千萬要注意,如果資料夾沒有檔案的話,程式會自動建立檔案;如果有檔案的話,程式會刪除原來就有的檔案,在建立一個檔案,也就是覆蓋原檔案。

  1. 多行寫入
filename = 'programming.txt'

with open(filename, 'w') as file_object:
	file_object.write('I love programming.\n')
	file_object.write('I love creating new game.\n')

記得每一句話在需要換行的地方都要加’\n’,不然語句會擠在一起。

  1. 附加到檔案
filename = 'programming.txt'

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 brower.\n')

這裡使用’a’來表示進行附加模式,將語句寫到檔案的後面,而不是覆蓋檔案。

動手試一試:

# 10-3
filename = 'guest.txt'

while True:
	name = input('請輸入你的名字:')
	if name == 'quit':
		break
	with open(filename, 'a') as file_object:
		file_object.write(name)
# 10-4
import time
filename = 'guest_book.txt'
while True:
	name = input('請輸入你的名字:')
	if name == 'quit':
		break;
	print(name + ', 歡迎你登入!')
	with open(filename, 'a') as file_object:
		file_object.write(name + '於' + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + '進行登入' + '.\n')

三、異常
python使用異常的特殊物件來管理程式執行期間發生的錯誤。
如果你未對異常進行處理,程式將停止,並顯示一個traceback,其中包含有關異常的報告。

  1. 處理ZeroDivisionError異常

下面來看一種導致Python引發異常的簡單錯誤。

print(5/0)

OK,這個程式執行時肯定會報錯,眾所周知,數字是不能除以0的,233。
下面我們來看一下如何處理。

  1. 使用try-except程式碼塊
try:
	pritn(5/0)
except:
	print("You can't divide by zero!")

這裡我們可以看到try-except程式碼塊的使用方法,在try中寫入可能或必定233會出錯的程式碼,當try中程式碼出錯時,程式將會執行except中的語句。

  1. 使用異常避免崩潰

發生錯誤是,如果程式還有工作沒有完成,妥善地處理錯誤就尤其重要。
當你寫完一個程式的時候,總有一些人為因素導致的錯誤,就比如上面的ZeroDivisionError,雖然你知道不能除零,但總有人會試試233。

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: ')
	if second_number == 'q':
		break;
	answer = int(first_number)/int(second_number)
	print(answer)

類似這樣,當然你以後可能會寫更復雜的程式,更應該要寫好異常,有助於發現錯誤。

  1. 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('Second number: ')
	if second_number == 'q':
		break;
	try:
		answer = int(first_number)/int(second_number)
	except ZeroDivisionError:
		print('You can't divide by 0!')
	else:
		print(answer)

在上面程式碼中,如果沒有發生錯誤,程式執行完try程式碼塊後,會執行else程式碼塊,不執行except程式碼塊;如果發生錯誤,首先在try程式碼塊中報錯的語句是不能執行的,然後程式會執行except語句,不執行else程式碼塊。

  1. 處理FileNotFoundError異常
filename = 'alice.txt'

try:
	with open(filename) as f_obj:
		contents = f_obj.read()
except FileNotFoundError:
	msg = "Sorry, the file " + filename + " does noe exist."
	print(msg)
  1. 分析文字
filename = 'alice.txt'

try:
	with open(filename) as f_obj:
		contents = f_obj.read()
except FileNotFoundError:
	msg = "Sorry, the file " + filename + " does noe exist."
	print(msg)
else:
	# 計算檔案大致包含多少個單詞
	words = contents.split()
	num_words = len(words)
	print("The file " + filename + " has about " + str(num_words) + " words.")
  1. 使用多個檔案

def count_words(filename):
	try:
		with open(filename) as f_obj:
			contents = f_obj.read()
	except FileNotFoundError:
		msg = "Sorry, the file " + filename + " does noe exist."
		print(msg)
	else:
		# 計算檔案大致包含多少個單詞
		words = contents.split()
		num_words = len(words)
		print("The file " + filename + " has about " + str(num_words) + " words.")

filename = 'alice.txt'
count_words(filename)
  1. 失敗時一聲不吭

def count_words(filename):
	try:
		with open(filename) as f_obj:
			contents = f_obj.read()
	except FileNotFoundError:
		pass
	else:
		# 計算檔案大致包含多少個單詞
		words = contents.split()
		num_words = len(words)
		print("The file " + filename + " has about " + str(num_words) + " words.")

filename = 'alice.txt'
count_words(filename)
  1. 決定報告那些錯誤
    ……

動手試一試:

# 10-6
while True:
	first_number = input('\nFirst number: ')
	if first_number == 'quit':
		break;
	second_number = input('Second number: ')
	if second_number == 'quit':
		break;
	try:
		result = int(first_number) + int(second_number)
	except ValueError:
		print('請輸入數字!')
	else:
		print(result)
# 10-7
while True:
	first_number = input('\nFirst number: ')
	if first_number == 'quit':
		break;
	second_number = input('Second number: ')
	if second_number == 'quit':
		break;
	try:
		result = int(first_number) + int(second_number)
	except ValueError:
		print('請輸入數字!')
	else:
		print(result)
# 10-8
def read_file(filename):
	try:
	with open(filename) as f_obj:
		lines = f_obj.readlines();
	except FileNotFoundError:
		print('File not found')
	else:
		for line in lines:
			print(line.rstrip())

cats = 'cats.txt'
dogs = 'dogs.txt'
read_file(cats)
rad_file(dogs)
# 10-9
def read_file(filename):
	try:
	with open(filename) as f_obj:
		lines = f_obj.readlines();
	except FileNotFoundError:
		pass
	else:
		for line in lines:
			print(line.rstrip())

cats = 'cats.txt'
dogs = 'dogs.txt'
read_file(cats)
rad_file(dogs)
# 10-10
def count_words(filename):
	try:
		with open(filename) as f_obj:
			contents = f_obj.read()
	except FileNotFoundError:
		pass
	else:
		print(contents.lower().count('the'))

filenames = ['Slavery in History.txt', 'John Lackland.txt']
for filename in filenames:
	count_words(filename)

四、儲存資料
這一節中使用學習使用json進行儲存資料。

  1. 使用json.dump()和json.load()
import json

numbers = [2, 3, 5, 7, 11, 13]

filename = 'numbers.json'
with open(filename, 'w') as f_obj:
	json.dump(numbers, f_obj)

使用json.dump()儲存資料

import json

filename = 'numbers.json'
with open(filename) as f_obj:
	numbers = json.load(f_obj)

print(numbers)

使用json.load()讀取資料

  1. 儲存和讀取使用者生成的資料
import json

filename = 'username.json'
try:
	with open(filename) as f_obj:
		username = json.load(f_obj)
except FileNotFoundError:
	username = input("What is your name?")
	with open(filename, 'w') as f_obj:
		json.dump(username, f_obj)
		print("we'll remember you when you come back, " + username + "!")
else:
	print("Welcome back, " + username + "!")

這段程式碼是前面的整和,對各塊知識的應用。

  1. 重構
    這一小節裡要學習使方法的任務簡單化……

首先,先把上面的程式碼變成一個函式:

import json

def greet_user():
	filename = 'username.json'
	try:
		with open(filename) as f_obj:
			username = json.load(f_obj)
	except FileNotFoundError:
		username = input("What is your name?")
		with open(filename, 'w') as f_obj:
			json.dump(username, f_obj)
			print("we'll remember you when you come back, " + username + "!")
	else:
		print("Welcome back, " + username + "!")
greet_user()

接下來,我們把讀取使用者名稱的方法分離,重構greet_user()方法

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()

最後,再把寫入資料拆出來,重構greet_user()

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 get_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():
	"""問候使用者,並指出名字"""
	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()

動手試一試:

# 10-11
# 寫入檔案
import json

filename = 'favorite_number.json'
favorite_number = int(input('input your favorite number: '))
with open(filename, 'w') as f_obj:
	json.dump(favorite_number, f_obj)
# 讀取檔案
import json

filename = 'favorite_number.json'
with open(filename) as f_obj:
	favorite_number = json.load(f_obj)
print("I know your favorite number! It's " + str(favorite_number))
# 10-12
import json

filename = 'favorite_number.json'
try:
	with open(filename) as f_obj:
		favorite_number = json.load(f_obj)
except:
	favorite_number = int(input('input your favorite number: '))
	with open(filename, 'w') as f_obj