《Python编程从入门到实践》学习笔记<10>:文件和异常

吃可爱长大的小学妹 提交于 2020-02-14 00:17:37
############################################################################################
#一些你必须要知道的概念
#1、异常是Python创建的特殊对象,用于管理程序运行时出现的错误,
#   出现异常会显示一个traceback,其中包含异常日志
#2、json模块能够对字典进行处理,也能够保存数据
#3、函数open()用于打开文件,主要接收的参数是文件名
#4、重构是将代码进行进一步的划分,将其归纳为完成具体工作的函数,让带吗更加清晰、易于理解和扩展
############################################################################################



#读取整个文件
#编辑文件pi_digits.txt,存放在tesxt_files目录中
#在windows中访问tesxt_files目录中的文件,需要在文件路径后面加反斜杠,后跟文件名即可
#若文件与程序所在目录一致,也可以不加文件路径
#在linux下文件路径的反斜杠需改成正斜杠
#函数open()用于打开文件
#关键字with用于在不需要访问文件后将其关闭
#as用于起别名,file_object既是别名
#read()方法用于文件读取,将文件pi_digits.txt中的内容读取后,将其作为字符串存储在变量contents中
#rstrip()方法用于删除字符串末尾
with open('tesxt_files\pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
    
    


#逐行读取
#将文件pi_digits.txt的名称存储在变量filename中
#调用open()fangfa,将文件内容存储到变量filename中
#用for循环,逐行读取文件内容
filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)
        
        


#创建包含文件内容的列表,用于存储文件内容,在with代码块以外能够读取文件内容
#readlines()方法可以拂去文件中的每一行内容,将其存储在列表中
#read()读取整个文件、readline()读取一行文件、readlines()读取每一行文件
#for循环用于读取列表line中的值
filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line)




#使用文件的内容
#存储完文件内容后,对文件内容进行的操作
filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

#创建变量pi_string,赋值空字符串
pi_string = ''
#循环读取列表line,并将其拼接到pi_strin变量值的后面
#由于pi_string变量赋值为空,实际上就是将列表中的值加入变量pi_string中
for line in lines:
    #strip()方法将所有空行删掉,这样就会让结果变成不间断的字符串,方便截取
    pi_string += line.strip()

#float()方法将输出结果转为float类型
print(float(pi_string))
print(len(pi_string))
#由于readlines()方法的左右,使变量lines成为列表,并存储了文件的值,因此可以用访问列表的方式访问
print(pi_string[:5])







#测试生日是否在圆周率中
filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip()

birthday = input("Enter your birthday,in the form mmddyy:")
if birthday in pi_string:
    print("You birthday appends in the first million digits of pi!")
else:
    print("You birthday does not appear in the first million digits of pi.")
    
#输出结果如下所示:
Enter your birthday,in the form mmddyy:141592
You birthday appends in the first million digits of pi!




#10-1-1
#定义文本文件test1.txt存放在与程序相同的文件路径下,打开文件,并将文件赋给file_object1
with open("test1.txt") as file_object1:
    定义变量line1,用read()方法读取整个文件,并将文件的内容存储进line1中
    line1 = file_object1.read()
    print(line1)

#10-1-2
file = 'test1.txt'
with open(file) as file_object2:
    for line2 in file_object2:
        print(line2)
        
#10-1-3
file = 'test1.txt'
with open(file) as file_object2:
    lines = file_object2.readlines()

line3 = ''
for line in lines:
    line3 += line.strip()

print(line3)


#10-2
#replace()只能修改字符串,因此将文件内容放到列表中还需要将列表中内容拿出来
#所以直接将文件内容放入变量中当做赋值的字符串进行修改
with open('test1.txt') as file_object:
    lines = file_object.read()
    line = lines.replace('dog','cat')
    print(line)
    
    
    
    
    
    
    
#写入文件的操作
#python只能讲字符串内容写入到文本中,要写入数值,徐现将数值用str()方法转化为字符串
#创建变量filename用于存储需要写入的文件名programing.text,若没有该文件则自动建立该文件
filename = 'programing.text'

#调用变量programing.text,打开文件programing.text,并通过'w'赋予写入操作权限
#若该文件之前已存在,则执行'w'操作后,将自动清除文件之前的内容,再写入操作的内容
#若不想删除文件之前的内容,则可以使用附加模式操作,即带入模式实参'a',此时文件内容可以保留
#('w')进入写入模式,('r')进入读取模式,('a')进入附加模式,('r+')进入读取和写入文件的模式
#若省略了模式实参,则系统默认为只读模式
with open(filename,'w') as file_object:
    #write()方法用于文件写入,括号内是需要写入的内容
    file_object.write("I love proggramming.")
    
    

#例题变种
#创建变量filename用于存储需要写入的文件名programing.text,若没有该文件则自动建立该文件
filename = 'programing.text'

#打开文件pi_digits.txt,并将文件内容存入变量lines
with open('pi_digits.txt') as file_object:
    lines = file_object.read()

#将变量lines中的字符串内容写入文件programing.text中
with open(filename,'w') as file_object1:
    file_object1.write(lines)
    
    
    


#10-3
filename = 'programing.text'

name = input("请输入您的名:")
with open(filename,'w') as file_object1:
    file_object1.write(name)

#将写入文件的内容展示出来
with open(filename) as file_object2:
    lines = file_object2.read()
print(lines)




#10-4
#导入模块os
import os
#调用os中类path中的方法isfile,用来判断文件guest_book.txt是否存在
if os.path.isfile("guest_book.txt"):
    
    os.remove('guest_book.txt')
    print("------删除原始文件------\n")
else:
    print("------没有原始文件------\n")

name_guest1 = []
filename = 'guest_book.txt'

while True:
    name = input("请输入您的名:")
    if name != 'q':
        name_string = "Hello," + name + "!"
        name_guest1.append(name_string)
    else:
        break

for guest1 in name_guest1:
    with open(filename,'a') as file_object:
        file_object.write(guest1 + "\n")

with open(filename) as file_object1:
    line = file_object1.read()
    print(line)





#10-5(不想老问人家为啥喜欢编程,干脆写谁会啥武功吧)
#与上例相同,删除已有文件
import os

if os.path.isfile("wugong_record.txt"):
    os.remove('wugong_record.txt')
    print("------删除原始文件------\n")
else:
    print("------没有原始文件------\n")


file_name = "wugong_record.txt"
#创建空字典you_name_wugong用于存储姓名和擅长武功的键值对
you_name_wugong = {}

while True:
    name = input("请输入你的名字:\n")
    #为了少打几个字,当输入为1的时候跳出
    if name == '1':
        break
    wugong = input("请输入你擅长的武功:\n")
    if wugong == '1':
        break
    you_name_wugong[name] = wugong

for key,value in you_name_wugong.items():
    name_wugong = key + ":" + value + "\n"
    print(name_wugong)
    #文件写入的时候,需要将编码改成utf-8,这样可以阻止中文乱码的现象
    with open(file_name,'a',encoding='utf-8') as file_object:
        lines = file_object.write(name_wugong)

print(you_name_wugong)




#使用try-except代码块处理ZeroDivisionError异常
#异常捕获后,如果后续还有其他代码,其他代码继续执行
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")


#编写下例while循环,当输入除数为零时,系统报错,此时需加入异常捕获机制
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("Second number:")
    if second_number == 'q':
        break
    answer = int(first_number) / int(second_number)
    print(answer)
    
#经过改写后,加入了异常捕捉机制try--except--else
#try--except--else的运行机制是
#将逻辑放入try代码块中执行
#将异常信息或情况放入except中
#当程序不报错时,输出else中的值
#否则输出异常情况的值
#该方法用于处理可能会发生的错误
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("Second number:")
    #输入second_number后,执行try封装的代码块
    try:
        #执行answer变量封装的逻辑
        answer = int(first_number) / int(second_number)
    #出现ZeroDivisionError异常的时候
    except ZeroDivisionError:
        #输出下列语句
        print("You casn't divide by 0 !")
    #否则
    else:
        #输出变量answer的值
        print(answer)




#执行下例时,由于文件本身不存在,因此会报错FileNotFoundError,解决类似异常可以使用如下方式
filename = 'alice.txt'

with open(filename) as f_obj:
    contents = f_obj.read()
    
    
#经过改写后,增加异常处理机制try--except
#执行try封装的代码块,当出现异常时,except捕获异常FileNotFoundError
#捕获异常后,创建变量msg并输出
filename = 'alice.txt'

try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
    
    


#创建文本alice.txt,内存Alice in Wordlands小说英文原文
#split()方法用于通过指定分隔字符,来分割字符串,若不设定,则默认为空格
filename = 'alice.txt'

#try--except用于异常捕获处理
try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
#1无异常则继续执行
else :
    # 计算文件大致包含多少个单词
    #创建变量words,用于存放被split()方法指定空格分割contents变量后的值
    words = contents.split()
    #统计变量words中元素的长度
    num_words = len(words)
    #输出结果
    print("This file " + filename + " has about " + str(num_words) + " words.")
    
    
    
#创建方法count_words(),带入形参filename
def count_words(filename):
    """计算一个文件大致包含多少单词"""
    #try--except用于异常捕获
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        #msg = "Sorry, the file " + filename + " does not exist."
        #print(msg)
        #在异常处理中,pass的作用是当异常出现时,可以不显示直接跳过
        pass
    #未出现异常结果时执行else部分代码
    else:
        #计算文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")

#带入实参filenames,且实参filenames为列表
filenames = ['alice.txt','Robert_Louis_Stevenson.txt']
#循环读取列表中的元素,并赋值给filename
for filename in filenames:
    #用filename循环调用方法count_words()
    count_words(filename)
    
    
    
    
#创建变量ff,保存文本'minss_files.txt'
ff = 'minss_files.txt'

def count_words(filename):
    """计算一个文件大致包含多少单词"""
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        #创建变量with,用于捕获异常后封装输出
        msg = "Sorry, the file " + filename + " does not exist."
        #给ff执行写入权限
        with open(ff,'a') as f_d:
            #将捕获的异常信息写入文件中
            f_d.write(msg)
    else:
        #计算文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")

filenames = ['alice.txt','Robert_Louis_Stevenson.txt','little_women.txt']
for filename in filenames:
    count_words(filename)
    
    
    
    
    
#10-6、10-7
#输出提示信息
print("这是一个加法运算,请按照提示往下进行!\n")
#创建while循环
while True:
    #try--except用于异常捕获处理
    try :
        #输入first_number,last_number的值,并用int()进行数值类型转换,变为数值型数据
        first_number = int(input("请输入第一个数字:\n"))
        last_number = int(input("请输入第二个数字:\n"))
    #当输入数值为字符型数据时,会报错ValueError,此时将该异常捕获
    except ValueError:
        #针对异常输出
        msg = "请您输入整数!"
        print(msg)
    #若无异常则执行else处代码
    else:
        number = first_number +last_number
        print("最后的计算结果为:" + str(number) + "!\n")
        
        
        
#10-8、10-9
#定义方法count_peets,带入形参filename
def count_peets(filename):
    """读取文档中的动物名称""" 
    #try--except用于异常捕获处理
    try:
        with open(filename) as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        msg = '抱歉,没有' + filename + '文件。'
        print(msg)
    else:
        print(filename + "文件里面有:")
        print(contents + '\n')
        #若将else出的输出逻辑改为pass,则实现10-9需求

filenames = ['cats.txt','dogs.txt']
for filename in filenames:
    count_peets(filename)
    
    
    

#10-10
def count_peets(filename):
    """读取文档中的动物名称"""
    try:
        with open(filename) as file_obje  ct:
            contents = file_object.read()
    except FileNotFoundError:
        msg = '抱歉,没有' + filename + '文件。'
        print(msg)
    else:
      vocabulary = contents.lower().split().count('is')
      print(vocabulary)

filenames = ['alice.txt','Robert_Louis_Stevenson.txt']
for filename in filenames:
    count_peets(filename)
    
    
    

#调用json模块
#json模块能够将简单的Python数据结构转储到文件中
#并在程序再次运行时加载文件中的数据
import  json

number = [2,3,5,7,11,13]

filename = 'number.json'
with open(filename,'w') as file_object:
    #json.dump()用于将变量number的值写入json文档file_object中
    json.dump(number,file_object)
    

#调用json模块
import json

filename = 'number.json'
with open(filename) as file_object:
    #json.load()用于读取json文档中的数据
    #若文档中无数据,则会报错
    numbers = json.load(file_object)

print(numbers)






----------------------------------------------------------------------------------------------------
#重构
#调用json模块
import json
#如果以前存储了用户名,就加载它,否则就提示用户输入用户名并存储它
#创建变量filename,并赋值'username.json'
filename = 'username.json'
#try--except用于异常捕获处理
try:
    #当能够读取filename时
    with open(filename) as f_obj:
        #调用json.load()函数对json文件进行读取,并将内容赋值给变量username
        username = json.load(f_obj)
#except捕获到异常信息FileNotFoundError后执行如下操作
#当程序无法读取filename内容时,新建username.json文件,并生成内容
except FileNotFoundError:
    #调用input方法输入姓名,并赋值给变量username
    username = input("What is your name?")
    #filename文档存在时打开,不存在时新建,并通过'w'赋予写入权限
    with open(filename,'w') as f_obj:
        #将username的值通过json.dump()方法写入到filename中去
        json.dump(username,f_obj)
        print("We'll remember you when you come back," + username + "!")
else:
    print("Welcome back, " + username + "!")
----------------------------------------------------------------------------------------------------
#整理上例中的代码,将其重构
import json
#将处理过程封装入greet_user()方法中,调用该方法就可以实现需求
def greet_user():
    """问候用户,并指出其名字"""
    filename = 'username.ison'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        username = input("What is your name?")
        with open(filename,'w') as f_obj:
            json.dump(username, f_obj)
            print("We'll remember you when you come back," + username + "!")
    else:
        print("Welcome back, " + username + "!")

greet_user()
----------------------------------------------------------------------------------------------------
#对上例再次进行重构,拆分成更多方法,方便调用
import json
#定义方法get_stored_username,将try--except--else异常捕获机制进行封装,根据异常情况返回不同结果
def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

#定义方法greet_user,将方法get_stored_username输出的返回值进行处理
def greet_user():
    """问候用户,并指出其名字"""
    #调用有返回值的方法,需要提供一个变量用来存储结果
    username = get_stored_username()
    #if判断,当条件为真时
    if username:
        print("Welcome back," + username + "!")
    else:
        username = input("What is your name?")
        filename = 'username.json'
        with open(filename,'w') as f_obj:
            json.dump(username,f_obj)
            print("We'll remember you when you come back," + username + "!")

greet_user()
----------------------------------------------------------------------------------------------------
#对上例再次进行重构,将每一步都拆成对应的方法
import json

def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username
#方法get_new_username()用于构建文档username.json,并写入数据
def get_new_username():
    """提示用户输入姓名"""
    username = input("What is your name?")
    filename = 'username.json'
    with open(filename,'w') as f_obj:
        json.dump(username,f_obj)
    return username

def greet_user():
    """问候用户,并指出其名字"""
    #调用get_stored_username,当文档存在时,直接输出
    username = get_stored_username()
    if username:
        print("Welcome back," + username + "!")
    #当文档不存在时,调用方法get_new_username()生成新的文档并输出
    else:
        username = get_new_username()
        print("We'll remember you when you come back," + username + "!")

greet_user()




#10-11
import json
filename = 'test.json'
username = input("随便写点啥:\n")
with open(filename,'w') as f_obj:
    json.dump(username,f_obj)

with open(filename) as f_obj:
    number = json.load(f_obj)
    print(number)
    



#10-12
import json

def like_number():
    filename = 'number.json'
    try:
        with open(filename) as f_obj:
            number = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return number

def new_number():
    number = input("输入你喜欢的数字!")
    filename = 'number.json'
    with open(filename,'w') as f_obj:
        json.dump(number,f_obj)
    return number

def number():
    number = like_number()
    if number:
        print("我喜欢的数字为:" + number + "!")
    else:
        number = new_number()
        print("已经添加了你喜欢的数字!")

number()



#10-13
import json

def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username
        
def get_new_username():
    """提示用户输入姓名"""
    username = input("请输入您的名字:\n")
    filename = 'username.json'
    with open(filename,'w') as f_obj:
        json.dump(username,f_obj)
    return username

def judge_name(real_name):
    """对输入的用户名进行判断"""
    username = get_stored_username()
    if real_name == '1':
        print("欢迎回来," + username + "!")
    elif real_name == '2':
        username = get_new_username()
        print("我们将重新录入" + username + "这个名字!")
    else:
        print("您的输入有误,请重新执行程序!")

def greet_user():
    """问候用户,并指出其名字"""
    username = get_stored_username()
    print("请问," + username + "的用户名是否正确?")
    real_name = input("(正确请输入1,错误请输入2!)\n")
    real_name = judge_name(real_name)

greet_user()

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!