打开文件:
使用`open()`函数打开文件,并获取文件对象。
with open('file_path', mode='r', encoding='utf-8') as file:文件操作代码
读取文件:
使用文件对象的`read()`、`readline()`或`readlines()`方法读取文件内容。
with open('file_path', mode='r', encoding='utf-8') as file:content = file.read() 读取整个文件内容line = file.readline() 读取一行内容lines = file.readlines() 读取所有行内容

写入文件:
使用文件对象的`write()`方法将内容写入文件。
with open('file_path', mode='w', encoding='utf-8') as file:file.write('Hello, World!') 写入内容
关闭文件:
使用`close()`方法关闭文件。
with open('file_path', mode='r', encoding='utf-8') as file:文件操作代码file.close() 关闭文件
