#練習題網站:https://www.xz577.com/j/129.html
#文件與異常
#同名文件下可打開
with open('pi.txt') as file_object:
contents=file_object.read()
print(contents)
print(contents.rstrip())
#read()函數會默認返回空行,所以可以用rstrip()刪除
#打開同目錄下的文件夾中包含的文件
with open('practice\pi.txt') as file_object: #windows使用反斜槓'\',當然正斜槓也可以
contents=file_object.read()
print(contents)
#打開任意處的文件:精確查找
with open('C:\CODING\.idea\practice\pi.txt') as file_object:
#上面的r是爲了保證萬無一失 因爲反斜在python裏面爲轉義字符
#讀取整個文件進行打印
contents=file_object.read()
print(contents.rstrip())
#逐行讀取 遍歷整個文件
source='C:\CODING\.idea\practice\pi.txt'
with open(source) as file_object:
for line in file_object:
print(line.rstrip()) #因爲默認會多空行所以用rtrip
#使用with時,open返回的對象只在with代碼塊中使用
#如果想要在with之外使用,那麼先將文件的各行儲存在列表中
source='C:\CODING\.idea\practice\pi.txt'
with open(source) as file_object:
lines=file_object.readlines()
#readlines讀取每行並存儲在列表中
#注意不是readline!!!
for line in lines:
print(line.rstrip())
#使用文件內的內容 此處是把pi存儲在字符串內
pi_string=''
for line in lines:
pi_string+=line.strip()
print(pi_string)
print(len(pi_string))
#如果想把字符串轉化爲數值 可以使用int或者float
a=float(pi_string)
print(a)
#10.2練習題
source='C:\CODING\.idea\practice\pi.txt'
#將python替換爲c
with open(source) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.replace('python','c').rstrip())
#寫入文件
#w爲寫入模式,r爲讀取模式,a爲附加模式,r+爲讀取和寫入
#注意當文件不存在時,將自動創建,但是當文件
#但是當文件不存在的時候將自動創建文件
#如果文件存在使用了w那麼原來的內容將被清除
file_name='p.txt'
with open(file_name,'w') as file_object:
file_object.write("I love python!!!\nAnd I am so crazy about programmming!!!")
#下面是三種方法:
with open(file_name) as file_object:
content = file_object.read()
print(content)
for line in file_object:
print(line.rstrip())
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
#寫入多行
file_name='p.txt'
with open(file_name,'w') as file_object:
file_object.write("hello world!\n") #注意此處如果不加\n那麼兩行就會變成一行
file_object.write("I love python!")
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip())
#附加模式寫入多行
with open(file_name,'a') as file_object:
file_object.write("\nlets do this\n")
#注意此處前面需要一個\n 否則會和成一行
file_object.write("I love python!")
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip())
#10.3練習 輸入訪客名稱
file_name='hello.txt'
with open(file_name,'w') as file_object:
a=input("Your name:")
file_object.write(a)
with open(file_name) as file_object:
con=file_object.read()
print(con.rstrip())
#10.4練習 多次輸入名字 每個名字一行
file_name='hello.txt'
with open(file_name,'w') as file_object:
active=True
while active:
a=input("Enter your name:")
print("Hello!"+a)
file_object.write(a+'\n')
b=input("Do you want to go on? YES PR NO")
if b!='YES':
active=False
with open(file_name) as file_object:
con=file_object.read()
print(con.rstrip())
#使用try-except代碼塊
try:
print(5/0)
except ZeroDivisionError:
print("You cannot divide by Zero!")
#使用代碼塊避免崩潰
while True:
f_n=input("First number:")
if f_n=='q':
break
s_n=input("Second number:")
if s_n=='q':
break
try:
answer=int(f_n)/int(s_n)
print(answer)
except ZeroDivisionError:
print("You cannot do this!")
#當然也可以使用else
try:
answer=int(f_n)/int(s_n)
except ZeroDivisionError:
print("You cannot do this!")
else:
print(answer)
#處理FileNotFoundError
file_name="pppp.txt"
try:
with open(file_name) as file_o:
con=file_o.read()
print(con.rstrip())
except FileNotFoundError:
print(file_name+".txt does not exist!")
#分析文本
file_name="hello.txt"
try:
with open(file_name) as f_o:
con=f_o.read()
except FileNotFoundError:
print("Sorry! The file cnnot be found!")
else:
words=con.split()
#split將字符串按照空格/行 切成列表
s=len(words)
print("The file "+file_name+".txt has about "+str(s)+" words.")
#爲了方面使用 可以設置函數
def count(file_name):
try:
with open(file_name) as f_o:
con = f_o.read()
except FileNotFoundError:
print("Sorry! The file cnnot be found!")
else:
words = con.split()
# split將字符串按照空格/行 切成列表
s = len(words)
print("The file " + file_name + ".txt has about " + str(s) + " words.")
file_name="hello.txt"
count(file_name)
#加循環
file_collection=['hello.txt','pp.txt','hahah.txt']
for file_name in file_collection:
count(file_name)
#自主選擇報告哪些程序錯誤
try:
--snip--
except:
pass
else:
--snip--
#10.6+10.7 練習 加法運算 實現多次輸入 錯誤提示
def adddd(a,b):
try:
a=int(a)
b=int(b)
except ValueError:
print("Please enter numbers instead of text.")
else:
print(a+b)
while True:
a=input("Enter the first number:")
b=input("Enter the second number:")
adddd(a,b)
c=input("Go on or not?YES OR NO")
if c!="YES":
break
#10.8練習 讀取文件 異常
file_name=['cats.txt','dogs.txt','hh.txt']
with open(file_name[0],'w') as file_o:
file_o.write("mory\njojo\nhapo")
with open(file_name[1],'w') as file_o:
file_o.write("mmory\njkkojo\nhhhhapo")
def read_name(a):
try:
with open(i) as ob:
con=ob.read()
print(con.rstrip())
except FileNotFoundError:
print("The file "+i+" cannot be found.")
for i in file_name:
read_name(i)
#存儲數據
#使用json模塊來進行存儲:將數據存儲在文件對象中,格式是列表
import json
numbers=[2,3,4,5]
file_name='numbersjson.txt'
with open(file_name,'w') as ob:#藉助ob對象最終把數據存儲在number.json裏面
json.dump(numbers,ob)
#用load函數來讀出
with open(file_name) as ob:
number=json.load(ob)
print(number)
#保存和讀取用戶輸入數據+重構
import json
def get_user():
file_name='usernamer.txt'
try:
with open(file_name) as file_ob:
username=json.load(file_ob)
except FileNotFoundError:
username=input("What's your name?")
with open(file_name,'w') as file_ob:
json.dump(username,file_ob)
print("We will remember when you are back,"+username+"!")
else:
print("Welcome back!"+username)
get_user()
#進而在另一個.py模塊中
import ha
ha.get_user()
#函數進一步的重構
import json
def get_user_stored():
file_name='userna.txt'
try:
with open(file_name) as file_ob:
username=json.load(file_ob)
except FileNotFoundError:
return None
else:
return username
def greet_use():
username=get_user_stored()
if username:
print("Welcome back!" + username)
else:
username=input("What's your name?")
file_name = 'userna.txt'
with open(file_name,'w') as file_ob:
json.dump(username,file_ob)
print("We will remember when you are back,"+username+"!")
greet_use()
#函數進進一步的重構
import json
def get_user_stored():
file_name='userna.txt'
try:
with open(file_name) as file_ob:
username=json.load(file_ob)
except FileNotFoundError:
return None
else:
return username
def get_new_name():#函數定義時的括號以及冒號!!!
username = input("What's your name?")
file_name = 'userna.txt'
with open(file_name, 'w') as file_ob:
json.dump(username, file_ob)
return username
def greet_use():
username=get_user_stored()
if username:
print("Welcome back!" + username)
else:
username=get_new_name()
print("We will remember when you are back,"+username+"!")
greet_use()
#重構是爲了目的性更強
#10.12 功能:
#記錄用戶輸入數字;
#存儲自定義文件內;
#如果不輸入數字提示並且可以重新輸入
#可以多次循環輸入
#紀念一下這個實現完整功能的程序!!奧利給!!
import json
def num_stored():
try:
f_n=input("What's your favorite number?\n")
with open(file_name,'w') as ob:
json.dump(f_n,ob)
f_n = int(f_n)
except ValueError:
print("Enter number please~")
return 0
def read_num(file_name):
with open(file_name) as ob:
con=json.load(ob) #有參數!!!
print("I know your favorite number is "+str(con)+".")
def enter_num(file_name):
while True:
num_stored()
read_num(file_name)
a=input("\nGO ON OR NOT? YES OR NO\n")
if a!="YES":
break
file_name=input("where you want to store your number?\n(plz end with'.txt')\n")
mm=num_stored()
while True:
if mm==0:
num_stored()
else:
enter_num(file_name)
oo=input("what to stop?YES OR NO")
if oo!='YES':
break
#10.13 實現
#詢問老名字是否是新用戶的名字,如果不是,提示重新輸入
import json
def username_stored():
username=input("What's your name?")
print("Hello! We will remember your name when you come back next time, "+username+"!")
file_name='hello.txt'
with open(file_name,'w') as ob:
json.dump(username,ob)
return username
def username_out():
file_name = 'hello.txt'
with open(file_name) as ob:
username=json.load(ob)
return username
def greet_comer():
old_name=username_out()
greet=input("Hello! Is "+str(old_name)+" your name?\nY or N\n")
if greet != 'Y':
username_stored()
print(username_out())
greet_comer()
#在另外一個同名文件夾下可以使用上面的函數
#只用greet_comer()就可以
#重構的好處是程序明確便於後期的修改 以及一個特定函數可以不斷嵌套在其他函數裏面 多次使用!
import ha
ha.greet_comer()
python第十章 文件與異常
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.