在Python中,open()函数用于打开文件,并返回文件对象。其基本语法如下:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)其中,参数含义如下:
file:文件路径mode:打开文件的模式,可选值有’r’(只读)、‘w’(写入)、‘a’(追加)、‘b’(二进制模式)、‘+’(读写模式)等buffering:缓冲设置,可选值为整数或者0encoding:指定文件编码errors:指定编码错误处理方案newline:设置换行符closefd:如果为False,则将fd传递给open()函数opener:用于打开文件的自定义函数示例:
# 打开文件并读取内容with open('example.txt', 'r') as file: content = file.read() print(content)# 打开文件并写入内容with open('example.txt', 'w') as file: file.write('Hello, World!') 

