#练习题网站: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第十章 文件与异常
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.