真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

Python----文件和異常-創(chuàng)新互聯(lián)

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

網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作服務(wù)團(tuán)隊(duì)是一支充滿著熱情的團(tuán)隊(duì),執(zhí)著、敏銳、追求更好,是創(chuàng)新互聯(lián)的標(biāo)準(zhǔn)與要求,同時竭誠為客戶提供服務(wù)是我們的理念。創(chuàng)新互聯(lián)把每個網(wǎng)站當(dāng)做一個產(chǎn)品來開發(fā),精雕細(xì)琢,追求一名工匠心中的細(xì)致,我們更用心!

#從文件中讀取數(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----文件和異常

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。


分享標(biāo)題:Python----文件和異常-創(chuàng)新互聯(lián)
瀏覽地址:http://weahome.cn/article/djcipg.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部