zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    栈:删除最外层的括号 (Leetcode 1021 / 155 / 1172 / 剑指31 / 面试 03.03)
    JDBC: Druid连接池
    JDBC: C3P0
    JDBC: C3P0
    JDBC: C3P0连接池
    JDBC: DBCP连接池
    JDBC: 数据库连接池
    JDBC: JDBC 控制事务
    JDBC: 预处理对象
    wpf 键盘快捷键响应
  • 原文地址:https://www.cnblogs.com/zhuanfang/p/13650528.html
Copyright © 2011-2022 走看看