• python基础14-文件、异常


    # 文件和异常:
    
    
    
    
    # 读取文件 --读取所有
    file = 'D:/liuzhuanfang/python/Hogwartsliu/xueqiu/file_read.txt'
    # 第2个实参定义 "w" --写入(删除原文件),"r" --读取,"a" --写入(原文件后添加),"r+" --读写
    with open(file,"r+") as f:  
        content1 = f.write("I love play5.
    ")  # "
    " --换行
        content2 = f.read()
        print(content2)
    
    
    
    # 读取文件 --按行读取
    file = 'D:/liuzhuanfang/python/Hogwartsliu/xueqiu/file_read.txt'
    with open(file) as f:
        for line in f:
            print(line.strip()) # 删除首尾空格
            time.sleep(2)
    
    
    # 读取文件
    file = 'D:/liuzhuanfang/python/Hogwartsliu/xueqiu/file_read.txt'
    with open(file) as f:
        lines = f.readlines()   # 文件读取后以 列表显示
    pi = ""
    for line in lines:
        pi+=line.strip()  # 组合成一个新的字符串
    print(lines[:10] + "...")  # 切片查询
    print(len(pi))
    
    
    
    
    # 异常处理:
    # try-except:出现异常 程序还能继续运行
    try:
        print(5/0)
    except ZeroDivisionError:
        print("you can't divide by zero !")
        
        
        
    # ZeroDivisionError --处理分子不能为0:
    while True:
        first = input("
     number1:")
        if first=="q":
            break        # 遇到break 直接退出循环
        second = input("number2:")
        if second =="q":
            break
        try:
            answer = int(first)/int(second)  # 执行条件
        except ZeroDivisionError:            # 条件异常抛出错误 并继续往后执行
            print("you can't divide by 0!")
        else:
            print(answer)
    
    
    
    
    # FileNotFoundError --处理文件找不到
    filenaem = "ali.txt"
    try:
        with open(filenaem) as f :
            contents = f.read()
    except FileNotFoundError:
        print("file is not fond")
        
        
    案例:
    def count(file):
        try:
            with open(file) as f :
                contents = f.read()
        except FileNotFoundError:
            pass  # 相当于 占位符
          # print(file +"file is not fond")
        else:
            words = contents.split(sep=",")  # 以逗号分隔
            num = len(words)
            print("the file"+ file + "has about " + str(num)+ " words.")
    
    file = 'D:/liuzhuanfang/python/Hogwartsliu/xueqiu/file_read1.txt'
    count(file)
  • 相关阅读:
    57. Insert Interval
    56. Merge Intervals
    55. Jump Game
    54. Spiral Matrix
    52. N-Queens II
    More Effective C++ 条款2 最好使用C++转型操作符
    More Effective C++ 条款1 仔细区别pointers和references
    Python_内置函数之max
    python_超级基础
    python_format格式化输出、while else、逻辑运算符、编码初识
  • 原文地址:https://www.cnblogs.com/zhuanfang/p/13650528.html
Copyright © 2020-2023  润新知