内置函数 open() 是处理文件的良好方法。此方法将检查文件是否存在于指定路径中,如果存在则返回文件对象,否则返回错误。
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) #where file specifies the path
该方法接受 8 个参数,其中一个是必需的,其余都是可选的。其中模式类型有许多选项(r:读取,w:写入,x:独占创建,a:追加,t:文本模式,b:二进制模式,+:更新(读写))
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 文件 | 类似路径的对象 | 必需 |
| 模式 | 模式(可选)- 打开文件时的模式。如果未提供,则默认为 'r' | 可选 |
| 缓冲 | 用于设置缓冲策略 | 可选 |
| encoding(编码) | 编码格式 | 可选 |
| errors(错误处理) | 一个字符串,指定如何处理编码/解码错误 | 可选 |
| 换行 | 换行模式如何工作(可用值:None, ' ', '\n', 'r', 和 '\r\n') | 可选 |
| closefd | 必须为 True(默认);如果给出其他值,将引发异常 | 可选 |
| opener | 自定义的开启器;必须返回一个打开的文件描述符 | 可选 |
如果文件存在于指定路径中,它将返回一个文件对象,该对象可用于读取、写入和修改。如果文件不存在,则会引发 FileNotFoundError 异常。
| 输入 | 返回值 |
|---|---|
| 如果文件存在 | 文件对象 |
# opens test.text file of the current directory
f = open("test.txt")
# specifying the full path
f = open("C:/Python33/README.txt")
输出
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
# opens the file in reading mode
f = open("path_to_file", mode='r')
# opens the file in writing mode
f = open("path_to_file", mode = 'w')
# opens for writing to the end
f = open("path_to_file", mode = 'a')
输出
Open a file in read,write and append mode.