# 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()