内置函数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” | 可选择的 | 
| 减轻 | 用于设置缓冲策略 | 可选择的 | 
| 编码 | 编码格式 | 可选择的 | 
| 错误 | 指定如何处理编码/解码错误的字符串 | 可选择的 | 
| 新行 | 换行符模式如何工作(可用值:无’ ‘,’ \n ‘,’ r ‘和’ \r\n ‘) | 可选择的 | 
| 关门了 | 必须为真(默认);如果给定为其他值,将引发异常 | 可选择的 | 
| 开启工具 | 定制的开瓶器;必须返回打开的文件描述符 | 可选择的 | 
打开()返回值
如果文件存在于指定的路径中,它将返回一个文件对象,该对象可用于读取、写入和修改。如果文件不存在,它将引发 FileNotFoundError 异常。
| 投入 | 返回值 |
| 如果文件存在 | 文件对象 |
Python 中open()方法的示例
示例 1:如何用 Python 打开文件?
 # 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.示例 2:提供打开模式()
 # 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. 原创文章,作者:QJNRR,如若转载,请注明出处:https://www.506064.com/n/325014.html
 
 微信扫一扫
微信扫一扫  支付宝扫一扫
支付宝扫一扫 