zoukankan      html  css  js  c++  java
  • 【Python编程:从入门到实践】chapter10 文件和异常

    chapter10 文件和异常
    10.1 从文件中读取数据
    10.1.1 读取整个文件
    with open("pi.txt") as file_object:
    contents = file_object.read()
    print(contents)
    print(contents.rstrip())//去掉空白行
    10.1.2 文件路径
    10.1.3 逐行读取
    filename = 'pi.txt'
    with open(filename) as file_object:
    for line in file_object:
    print(line)
    10.1.4 创建一个包含文件各行内容的列表
    使用with关键字,open()返回的文件对象只在with代码块内可用。
    filename = 'pi.txt'
    with open(filename) as file_object:
    lines = file_object.readlines()
    for line in lines:
    print(line.tstrip())
    10.1.5 使用文件的内容
    删除每行末尾的换行符 -> rstrip()
    删除每行左边的空格 -> strip()
    10.1.6 包含一百万位3的大型文件
    filename = 'pi.txt'

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

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

    print(pi_string[:52] + "...")
    print(len(pi_string))
    10.1.7 圆周率值中包含你的升入吗
    birthday = input("Enter your birthday,in the form mmddyy:")
    if birthday in pi_string:
    print("OK")
    else:
    print("No")
    10.2 写入文件
    10.2.1 写入空文件
    filename = "programming.txt"

    with open(filename,'w') as file_object:
    file_object.write("I love programming")
    10.2.2 写入多行
    10.2.3 附加到文件
    10.3 异常
    10.3.1 处理ZeroDivisionError异常
    10.3.2 使用try-except代码块
    try:
    print(5/0)
    except ZeroDivisonError:
    print("You can't divide by zero")
    10.3.3 使用异常避免崩溃
    10.3.4 else 代码块
    try:
    answer = int(first_number)/int(second_number)
    exception ZeroDivisionError:
    print("You can't divide by 0!")
    else:
    print(answer)
    10.3.5 处理FileNoFoundError异常
    filename = "alice.txt"

    try:
    with open(filename) as f_obj:
    contents = f_obj.read()
    excep FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exit"
    print(msg)
    10.3.6 分析文本
    split() //根据空格分割字符串到列表
    10.3.7 使用多个文件
    10.3.8 失败时一声不吭
    try:
    //...
    catch FileNotFoundError:
    pass
    else:
    --snip--
    10.4 存储数据
    10.4.1 使用json.dump()和json.load()
    //保存到文件
    import json

    numbers = [2,3,4,5,6,6]

    filename = 'numbers.json'
    with open(filename,'w') as file_object:
    json.dump(numbers,file_object)

    //读取到内存
    import json

    filename = 'numbers.json'
    with open(filename) as file_object:
    numbers = json.load(file_object)
    print(numbers)
    10.4.2 保存和读取用户生成的数据
    10.4.3 重构

    作者:长风 Email:844064492@qq.com QQ群:607717453 Git:https://github.com/zhaohu19910409Dz 开源项目:https://github.com/OriginMEK/MEK 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利. 感谢您的阅读。如果觉得有用的就请各位大神高抬贵手“推荐一下”吧!你的精神支持是博主强大的写作动力。 如果觉得我的博客有意思,欢迎点击首页左上角的“+加关注”按钮关注我!
  • 相关阅读:
    HEC-ResSim原文档
    水文模型大全
    用word发布博客到博客园
    给你的浏览器标题栏加上小图标
    系统性能调优必知必会学习
    系统性能调优必知必会学习
    容器化学习
    Redisson学习
    mysql回顾
    事物、源码学习,spring-tx
  • 原文地址:https://www.cnblogs.com/zhaohu/p/8099783.html
Copyright © 2011-2022 走看看