首页 > 编程语言 > 详细

python基础14-文件、异常

时间:2020-09-11 16:31:55      阅读:50      评论:0      收藏:0      [点我收藏+]
# 文件和异常:




# 读取文件 --读取所有
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.\n")  # "\n" --换行
    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("\n 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)

 

python基础14-文件、异常

原文:https://www.cnblogs.com/zhuanfang/p/13650528.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!