1. 程式人生 > >Python----文件和異常

Python----文件和異常

readlines 目錄 first images pen 打開 全部 gre 取數

1.從文件中讀取數據

#從文件中讀取數據

with open("pi_digits.txt") as file_abnormal: #open()函數:接受的參數是要打開文件的名稱,在當前目錄查找指定文件
contents = file_abnormal.read() #方法read():讀取文件的全部內容,到達文件末尾時返回一個空字符
print(contents)
print(contents.rstrip())
print(contents)
#文件路徑
#要讓Python打開不與程序文件位於同一目錄中的文件,需要提供文件路徑

#相對路徑行不通就使用絕對路徑
file_path = r‘C:\WiFi_log.txt‘ #絕對路徑,不能含中文
with open(file_path) as file_abnormal:
test = file_abnormal.read()
print(test)
#逐行讀取
#檢查其中的每一行

filename = ‘pi_digits.txt‘
with open(filename) as file_object: #使用關鍵字with時,open()返回的文件對象只在with代碼塊內可用
lines = file_object.readlines() #將文件各行存儲在一個列表中,只能在with碼塊外使用

#for line in file_object:
#print(line)
#print(file_object) #只是文件屬性?
#print(line.rstrip())
for lin in lines:
print(lin.rstrip())
print("\n")
#使用文件內容
pi_string = " "
for line in lines: #讀取文本文件時,Python將所有文本解讀為字符串
pi_string += line.strip() #strip():刪除空格

#pi_string += line.rstrip() #rstrip():清除空白行
print(pi_string)
print(len(pi_string))
print(pi_string[:52])
print("\n")

技術分享圖片

2.#寫入文件

filenames = ‘programming.txt‘ #創建文件名
with open(filenames,‘w‘) as file_object: #w:寫入模式
file_object.write("I love programming.\n") #文件對象方法write()將一個字符串寫入文件
file_object.write("I love creating new games.\n")
with open(filenames,‘a‘) as file_object: #‘a‘:附加模式把文件內容附加到文件末尾,而不是覆蓋內容
file_object.write("I love creating apps that can run in browser.")

技術分享圖片

3.存儲數據

import json #json模塊能將簡單的Python數據結構存儲到文件中
def greet_user():
filename = ‘username.json‘ #創建文件
try:
with open(filename) as f_log: #註意冒號,打開文件
username = json.load(f_log) #把文件內容加載到變量
except FileNotFoundError:
username = input("What is your name? ") #之前沒寫入則執行except
with open(filename,‘w‘) as f_log: #寫入模式
json.dump(username,f_log) #json.dump進去
print("We‘ll remember your when you come back, " + username + "!")
else:
print("Welcome back , " + username +"!")
greet_user()
#重構
#代碼可以正確的運行,但是可以將代碼分為一系列函數來完成

def get_stored_username():
filename = ‘username.json‘
try:
with open(filename) as f_log:
username = json.load(f_log)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
filename = "username.json"
with open(filename,‘w‘) as f_log:
username = input("What is your name? ")
json.dump(username,f_log)
return username
def new_greet_user():
username = get_stored_username()
if username:
print("Welcome back, " + username + ‘!‘)
else:
username = get_new_username()
print("We will remember you when you come back, " + username + ‘!‘)
#new_greet_user()
get_new_username()
new_greet_user()

技術分享圖片

4.異常

#處理ZeroDivisionError異常
#print(5/0)

print("\n")
#使用異常避免崩潰
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: ")
#if second_number == ‘q‘:
#break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You don‘t divide by 0!")

else:
    print(answer)

#處理FileNotFoundError異常
#filename = ‘init.txt‘

try:
with open(filename) as log_object:
contents = log_object.read()
except FileNotFoundError: #避免客戶或者*看到異常
print("\nSorry,the file "+ filename + "done‘t exit.")
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
#使用多個文件
def count_words(filename): #定義函數註意加形參
try:
with open(filename) as log_object:
contents = log_object.read()
except FileNotFoundError: * # 避免客戶或者
看到異常**
print("\nSorry,the file " + filename + "done‘t exit.")
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filename = ‘programming.txt‘
count_words(filename)
print("\n")
技術分享圖片

def count_words(filename):
try:
with open(filename) as log_object:
contents = log_object.read()
except FileNotFoundError: **# 避免客戶或者*看到異常
#print("\nSorry,the file " + filename + "done‘t exit.")
pass #失敗時一聲不吭,讓程序繼續運行
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filename = ‘programming.txt‘
count_words(filename)
filename = [‘programming.txt‘,‘pi_digits.txt‘,‘abc.txt‘]
for file in filename: #遍歷列表傳遞實參
count_words(file)

技術分享圖片

Python----文件和異常