Python 文件数据读写
文件数据读写 读写文件,本质上是请求操作系统打开一个文件对象,然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。 文件读取 使用 Python 内置 open() 函数,以 rt 的模式读取文件,如下示例: >> > f = open ( 'some.txt' , 'rt' ) 这行代码就表示打开一个文件,若是文件不存在,会抛出 IOError 的异常,并给出详细的信息提示: >> > f = open ( 'undefined.txt' , 'rt' ) Traceback ( most recent call last ) : File "<stdin>" , line 1 , in < module > FileNotFoundError : [ Errno 2 ] No such file or directory : 'undefined.txt' 当成功打开文件时,可使用 read() 函数读取文件的内容: >> > f . read ( ) 'Hello world!' 当数据读取完毕后,需要调用 close() 关闭文件。因为文件对象会占用资源,使用完毕后需要及时关闭释放资源。 >> > f . close ( ) 还有一种方法就是使用 with 语句,给被使用的文件创建一个上下文环境,这样文件对象就能够自动关闭。