
Python
open()函数来打开文件。语法:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参数说明:
1. file:要打开的文件的路径。
2. mode:打开文件的模式,如'r'为只读模式,'w'为写入模式,'a'为追加模式等。
3. encoding:文件编码,如'utf-8'、'gbk'等。
4. errors:编码错误的处理方法,如'ignore'忽略错误,'replace'用?代替错误字符等。
示例:
Python
# 打开文件
f = open('file.txt', 'r', encoding='utf-8')
# 读取文件内容
content = f.read()
# 输出文件内容
print(content)
# 关闭文件
f.close()
更多示例:
Python
# 打开文件并写入内容
f = open('file.txt', 'w', encoding='utf-8')
f.write('hello world')
f.close()
# 打开文件并逐行读取内容
f = open('file.txt', 'r', encoding='utf-8')
for line in f:
print(line.strip()) # 去除每行结尾的换行符
f.close()
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号