python制作简单excel统计报表1之with的简单用法

# coding=utf-8

def open_file():
    """使用with打开一个文件"""

    # 普通操作文件方法
    # f = open('./static/hello.txt', 'r', encoding='utf-8')
    # rest = f.read()
    # print(rest)
    # f.close()

    # with 语法
    # with open('./static/hello.txt', 'r', encoding='utf-8') as f:
    #     rest = f.read()
    #     print(rest)

    # with 语法内部相当于如下代码
    try:
        f = open('./static/hello.txt', 'r', encoding='utf-8')
        rest = f.read()
        print(rest)
    except:
        pass
    finally:
        f.close()


if __name__ == "__main__":
    open_file()

 

posted @ 2019-07-15 10:56  reblue520  阅读(338)  评论(0编辑  收藏  举报