如何在 python 中打开文件?
使用内置函数open就可以打开文件。先来看下python中对open函数的定义
fileobject=open(file_name[,access_mode][,buffering])
参数定义如下
access_mode表示文件模式。常见的模式有读模式,写模式,追加模式等。这个参数是可选的,如果不填,默认就是读模式。具体的文件模式列表在下面表格中列出。
buffering缓存标志
如果不填,默认值为0
值为1表示行缓存
值>1则代表缓冲区的大小(单位是字节)
值<0表示使用默认缓存区的大小
file_name表示要访问的文件路径名称,可以是相对路径,也可以是绝对路径。
具体的文件模式access_mode参数表如下
值功能描述
w写模式
r读模式
x写模式,创建一个文件,如果文件已存在,则报错
a追加模式
b二进制模式(可与其他模式结合使用)
+读/写模式(可与其他模式结合使用)
其中b或者+可与其他模式结合使用需要说明下:
如rb就表示读取一个二进制文件
如w+表示对打开的文件可读可写
如wb+则表示对二进制文件可读可写,如果模式中不加b则默认表示文本文件
以上内容为大家介绍了如何在python中打开文件?,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






