Python Unit10 文件&异常

"""============================================================================================="""
"""=========================================读取整个文件数据===================================="""
"""============================================================================================="""
"""
文件内容:
3.1415926535
8979323846
2643383279
"""

#相对文件路径
if 0:
    #没有close是因为python会自动合适的时候关闭
    #close关闭时机不恰当会引起报错
    with open('Unit10_testFile.txt') as file_object:
        contents = file_object.read()
        #.rstrip()剔除结尾多余的空行
        #因为.read()在末尾添加空字符,而空字符可能就会显示出空一行
        print(contents.rstrip())

    
#绝对文件路径
if 0:
    file_path = 'D:/Python/XXXXXX/Unit10_testFile.txt'
    with open(file_path) as file_object:
        contents = file_object.read()
        print(contents.rstrip())

"""============================================================================================="""
"""=========================================逐行读取文件数据===================================="""
"""============================================================================================="""
if 0:
    file_path = 'Unit10_testFile.txt'
    with open(file_path) as file_object:
        for line in file_object:
            #可以明显发现.rstrip()用处
            print(line.rstrip())

"""============================================================================================="""
"""=====================================创建一个包含文件各行内容的列表=========================="""
"""============================================================================================="""
if 0:
    file_path = 'Unit10_testFile.txt'
    with open(file_path) as file_object:
        #readlines() 从文件中读取每一行,并将其存储在一个列表中
        lines = file_object.readlines()

    for line in lines:
        print(line.rstrip())

if 0:
    file_path = 'Unit10_testFile.txt'
    with open(file_path) as file_object:
        #readlines() 从文件中读取每一行,并将其存储在一个列表中
        lines = file_object.readlines()

    pi_string = ''
    for line in lines:
        #strip()#剔除两端空白 第二章字符串有该内容
        #rstrip()#剔除末尾空白
        #lstrip()#剔除开头空白
        pi_string += line.strip()

    #打印整个文件
    print(pi_string)
    print(len(pi_string))

    #打印前15位小数点
    print(pi_string[:16]+'...')
    print(len(pi_string))    

"""============================================================================================="""
"""===============================================文件中查找数据================================"""
"""============================================================================================="""
if 0:
    file_path = 'Unit10_testFile.txt'
    with open(file_path) as file_object:
        lines = file_object.readlines()

    pi_string = ''
    for line in lines:
        pi_string += line.strip()
    
    SearchData = input("Search Data: ")

    if SearchData in pi_string:
        print("SearchData in pi_string")
        
    else:
        print("SearchData not in pi_string")

"""============================================================================================="""
"""===============================================字符串内容替换================================"""
"""============================================================================================="""
if 0:
    message = "I really like dogs."
    print('message:'+ message)
    message = message.replace('dog', 'cat')
    print('message:'+ message)  

"""============================================================================================="""
"""=============================================写入文件========================================"""
"""============================================================================================="""
if 0:
    filename = 'Unit10_ReadWriteFile.txt'
    #读取模式('r'或缺省)、写入模式 ('w')、读取写入模式('r+')、附加模式('a')
    #在读模式下:没有找到文件时他会报错
    #在写模式下:没有找到文件时他会自己创建一个
    #            已存在这个文件并这个文件带内容,原来文件数据会被覆盖
    #在附加模式:没有找到文件时他会自己创建一个
    #            已存在这个文件并这个文件带内容,原来文件数据不会被覆盖,只在其后增添内容
    #数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。
            
    with open(filename, 'w') as file_object:
        file_object.write("嘻嘻嘻.\n")
         
    with open(filename, 'w') as file_object:#嘻嘻嘻.将被覆盖掉
        #想要文本换行需要换行符'\n'
        file_object.write("I love programming.\n")
        file_object.write("I love creating new games.\n")
    
    #不覆盖原有文本内容使用附加模式打开文件
    with open(filename, 'a') as file_object:
        file_object.write("I also love finding meaning in large datasets.\n")
        file_object.write("I love creating apps that can run in a browser.\n")


"""============================================================================================="""
"""==========================================异常==============================================="""
"""============================================================================================="""
if 0:
    #显然 print(5/0) 会报错的,然后程序就不再继续执行了
    #添加 try-except 处理异常,程序会继续正常执行
    try:
        print(0/0)
    except ZeroDivisionError:
        print("You can't divide by zero!")

if 0:
    #利用pass代替语句遇到报错就不会提醒
    print("------------start------------")
    try:
        print(0/0)
    except ZeroDivisionError:
        pass
    print("-----------the-end-----------")


if 0:
    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
        try:#只有可能引发异常的代码才需要放在try语句中
            answer = int(first_number) / int(second_number)
            
        except ZeroDivisionError:#第一种报错可能 #被除数为零的报错
            print("You can't divide by 0!")
            
        except ValueError:#第二种报错可能 #输入字符的报错
            print("You can't string!")
            
        else:#仅在try 代码块成功执行时才需要运行的代码;这些代码应放在else 代码块中
            print(answer)


    
"""============================================================================================="""
"""=======================================分析文本=============================================="""
"""============================================================================================="""

if 0:
    #分析有多少个单词
    #使用split()方法根据字符串创建一个单词列表。split()通过空格来分割单词,显然判断中文有多少个字是不合适的
    title = "Alice in Wonderland."
    print(title.split())

"""============================================================================================="""
"""========================================储存数据============================================="""
"""============================================================================================="""


#JSON数据格式其他编程语言也可用
if 0:
    import json
    TestList_1 = [2, 3, 5, 7, 11, 13]
    filename = 'Unit10.json'
    #若文件已存在使用附加模式打开会报错
    #若文件不存在使用附加模式打开不报错
    #???追加数据怎么追加???
    with open(filename, 'w') as f_obj:
        json.dump(TestList_1, f_obj)

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


if 1:
    if 0:#程序合并前
        import json
        
        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 + "!")

        filename = 'username.json'
        with open(filename) as f_obj:
            username = json.load(f_obj)
            print("Welcome back, " + username + "!")

    if 1:#程序合并后
        import json
        # 如果以前存储了用户名,就加载它
        # 否则,就提示用户输入用户名并存储它
        
        filename = 'username.json'
        try:
            with open(filename) as f_obj:
                username = json.load(f_obj)
        except FileNotFoundError:
            username = input("What is your name? ")
            with open(filename, 'a') as f_obj:
                json.dump(username, f_obj)
                print("We'll remember you when you come back, " + username + "!")
        else:
            print("Welcome back, " + username + "!")     

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值