Python----文件和異常

1.從文件中讀取數(shù)據(jù)

創(chuàng)新互聯(lián)建站是一家集做網(wǎng)站、成都網(wǎng)站制作、網(wǎng)站頁面設(shè)計(jì)、網(wǎng)站優(yōu)化SEO優(yōu)化為一體的專業(yè)網(wǎng)站設(shè)計(jì)公司,已為成都等多地近百家企業(yè)提供網(wǎng)站建設(shè)服務(wù)。追求良好的瀏覽體驗(yàn),以探求精品塑造與理念升華,設(shè)計(jì)最適合用戶的網(wǎng)站頁面。 合作只是第一步,服務(wù)才是根本,我們始終堅(jiān)持講誠信,負(fù)責(zé)任的原則,為您進(jìn)行細(xì)心、貼心、認(rèn)真的服務(wù),與眾多客戶在蓬勃發(fā)展的市場環(huán)境中,互促共生。

#從文件中讀取數(shù)據(jù)

with open("pi_digits.txt") as file_abnormal: #open()函數(shù):接受的參數(shù)是要打開文件的名稱,在當(dāng)前目錄查找指定文件
contents = file_abnormal.read() #方法read():讀取文件的全部內(nèi)容,到達(dá)文件末尾時返回一個空字符
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: #使用關(guān)鍵字with時,open()返回的文件對象只在with代碼塊內(nèi)可用
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")
#使用文件內(nèi)容
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")

Python----文件和異常

2.#寫入文件

filenames = 'programming.txt' #創(chuàng)建文件名
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':附加模式把文件內(nèi)容附加到文件末尾,而不是覆蓋內(nèi)容
file_object.write("I love creating apps that can run in browser.")

Python----文件和異常

3.存儲數(shù)據(jù)

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

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

Python----文件和異常

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): #定義函數(shù)注意加形參
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")
Python----文件和異常

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 #失敗時一聲不吭,讓程序繼續(xù)運(yùn)行
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: #遍歷列表傳遞實(shí)參
count_words(file)

Python----文件和異常

新聞標(biāo)題:Python----文件和異常
地址分享:http://muchs.cn/article38/gedisp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、品牌網(wǎng)站設(shè)計(jì)、靜態(tài)網(wǎng)站、網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)