python-写入文件
一、写入空文件(覆盖)
# coding=UTF-8 filename = ‘test_text.txt‘ with open(filename, ‘w‘) as file_object: file_object.write("Add a word")
如果写入文件不存在,open()将自动创建它
如果文件已存在已有内容,会清空再写入
写入多行
# coding=UTF-8 filename = ‘test_text.txt‘ with open(filename, ‘w‘) as file_object: file_object.write("Add a word") file_object.write("Add two words")
加换行符
# coding=UTF-8 filename = ‘test_text.txt‘ with open(filename, ‘w‘) as file_object: file_object.write("Add a word\n") file_object.write("Add two words\n")
二、在原有文件上添加内容
用‘a’
# coding=UTF-8 filename = ‘test_text.txt‘ with open(filename, ‘a‘) as file_object: file_object.write("lalala\n") file_object.write("hahaha\n")
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16