Python open()
Python open()函数用于打开文件。
这是处理文件的第一步。
无论我们要读取,写入或者编辑文件数据,我们首先需要使用open()函数将其打开。
Python open()
Python open()函数语法为:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file:指定文件路径对象。
通常,一个str或者bytes对象代表文件路径。
这是一个强制性的论点。mode:指定文件打开模式。
有多种模式可以打开file.r:以只读模式打开文件。w:以写入模式打开文件,文件被截断。
x:打开以进行独占创建,如果文件已经存在则失败
a:可进行写入,如果存在则追加到文件末尾
b:二进制模式
t:文本模式(默认)
+:打开磁盘文件以进行更新(读取和写入)
File opened in binary mode return content of file as bytes without any decoding. Whereas files opened in text mode contents are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding.- buffering:可选整数,指定缓冲策略。
如果传递为0,则关闭缓冲。
仅当以二进制模式打开文件时才允许这样做。
如果传递为1,则使用行缓冲,并且仅在文本模式下才允许使用行缓冲。
如果传递的值大于1,则使用指定大小的固定大小的块缓冲区的字节。encoding:用于解码或者编码文件的编码名称。
仅应在文本模式下使用。errors:一个可选的字符串,指定如何处理编码和解码错误,不能在二进制模式下使用。
一些标准值是严格,忽略,替换等。newline:此参数控制通用换行模式的工作方式(仅适用于文本模式)。
可以是"无",""," \ n"," \ r"和" \ r \ n"。开瓶器:可以通过传递可调用的打开器来使用自定义开瓶器。
大多数时候,我们仅使用文件和模式参数来打开文件并对其执行必要的操作。
在文本模式下打开文件时,将返回" TextIOWrapper"实例。
当文件以二进制模式打开时,返回" BufferedRandom"实例。
Python打开文件
让我们看一些在python中打开文件的示例。
以文本和只读模式打开文件
# open file in text and read only mode f = open('data.txt', mode='r') print(type(f)) f.close()
输出: <class'_io.TextIOWrapper'>
以二进制和只读模式打开文件
f = open('favicon.ico', mode='r+b') print(type(f)) f.close()
输出: <class'_io.BufferedRandom'>
以二进制模式打开文件,只读和缓冲
f = open('favicon.ico', mode='br', buffering=16) f.close()
以二进制模式打开文件,只读且无缓冲
f = open('favicon.ico', mode='br', buffering=0) f.close()
以文本模式,只读和行缓冲打开文件
f = open('data.txt', mode='a', buffering=1) f.close()
使用截断以写入模式打开文本文件
f = open('data.txt', mode='w') f.close()
以独占创建模式打开文件
如果文件已经存在,则以" x"作为模式传递将抛出FileExistsError。
我们可以使用tryexcept块来捕获此异常并执行纠正措施。
try: f = open('data.txt', mode='x') except FileExistsError as e: print('file already exists')
输出:file already exists