'r'表示只读模式,文件必须存在,只能读不能写;'w'表示写入模式,文件不存在则创建,存在则清空覆盖。需用'a'追加、'r+'/'w+'/'a+'实现读写,加'b'可进行字节操作。
在 Python 的 open() 函数中,'w' 和 'r' 是文件打开模式(mode)的字符串标识,用来指定对文件的操作权限和行为。
'r' 表示只读模式(read)
mode 参数,Python 就用 'r'。 FileNotFoundError。 例如:
with open('data.txt', 'r') as f:
content = f.read() # 正常读取
# f.write('hello') # ❌ 报错:not writable'w' 表示写入模式(write)
立即学习“Python免费学习笔记(深入)”;
f.read() 会报错。 例如:
with open('output.txt', 'w') as f:
f.write('Hello, world!') # ✅ 写入,若文件存在则清空重写
# f.read() # ❌ 报错:not readable⚠️ 注意:

'a'(append)模式。 'r+'(文件必须存在)、'w+'(会清空)或 'a+'(从末尾追加,可读可写)。 \n → \r\n 在 Windows),如需原始字节操作,加 'b',如 'rb'、'wb'。不复杂但容易忽略