python的open方法的参数和文件方法概览 |
您所在的位置:网站首页 › python中调用open函数打开文件,调用close › python的open方法的参数和文件方法概览 |
Python File(文件) 方法
open() 方法
Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。 注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。 open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)(默认为r)。 open(file, mode='r') open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)参数说明: file: 必需,文件路径(相对或者绝对路径)。 mode: 可选,文件打开模式 buffering: 设置缓冲 encoding: 一般使用utf8 errors: 报错级别 newline: 区分换行符 closefd: 传入的file参数类型 opener:?file 对象使用 open 函数来创建,下表列出了 file 对象常用的函数:
在 write 内容后,直接 read 文件输出会为空,是因为指针已经在内容末尾。 两种解决方式: 其一,先 close 文件,open 后再读取,其二,可以设置指针回到文件最初后再 read # -*- coding: UTF-8 -*- import os; document = open("testfile.txt", "w+"); print "文件名: ", document.name; document.write("这是我创建的第一个测试文件!\nwelcome!"); print document.tell(); #输出当前指针位置 document.seek(os.SEEK_SET); #设置指针回到文件最初 context = document.read(); print context; document.close();PS:尽量使用with as打开文件 (主要内容来源https://www.runoob.com/python/file-methods.html,感谢作者辛勤付出) |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |