调用open(filename,'#')时需要另一个实参#,告诉Python你要写入打开的文件
'r':读取模式
'w':写入模式
'a':附加模式
'r+':读取和写入模式
如果没有参数,Python以默认的只读模式打开文件
- 写入空文件
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love promming.")
打开programming.txt看见 I Love programming
如果要写入的文件不存在,函数open()将自动创建它。然而,以写入('w')模式打开文件时千万小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
注意:Python只能将字符串写入到文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。
- 写入多行
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love promming.\n")
file_object.write("I love creating new games.\n")
结果如下:
注意:一定要添加\n否则,都是并排
- 附加到文件
如果要给文件添加内容,而不是覆盖原有的内容、可以附加模式打开文件。如果指定文件不存在,Python将为你创建一个空文件
filename = 'programming.txt'
with open(filename, 'a') as file_object:
file_object.write("I also love meaning in large datasets.\n")
file_object.write("I love creating apps that can run un a browser.\n")