python3(三十五)file read write
""" 文件读写 """ __author__on__ = 'shaozhiqi 2019/9/23' # !/usr/bin/env python3 # -*- coding: utf-8 -*- # 读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符 f = open('D:/temp/shao.txt', 'r', encoding='UTF-8') print(f.read()) f.close() # 执行结果 # 1.ashahh # 2.343erer # 文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的 # ---------------------------------------------------------- # 反之文件不存在的异常 try: f = open('D:/temp/shao.txt', 'r', encoding='UTF-8') print(f.read()) finally: if f: f.close() # ----------------------------------------------------------- # 简化上述方法 # 这和前面的try ... finally是一样的,但是代码更佳简洁,并且不必调用f