python将数据可追加的、多个数据分别写入到本地txt文件

第一种,之间open打开,但是最后需要用.close()关闭。 

'''
 w 只能操作写入 r 只能读取 a 向文件追加
 w+ 可读可写 r+可读可写 a+可读可追加
 wb+写入进制数据
 w模式打开文件,如果而文件中有数据,再次写入内容,会把原来的覆盖掉
'''
# 打开txt文件
file_handle=open('123.txt',mode='w')
#  第一种: write 写入 \n 换行符
file_handle.write('hello word 你好 \n')
# 第二种: writelines()函数 写入文件,但不会自动换行 
# file_handle.writelines(['hello\n','world\n','你好\n','智游\n','郑州\n'])
# 关闭文件
file_handle.close()

第二种,利用with打开,不需要用.close()操作关闭,会自动关闭。

# 覆盖写入
with open("text.txt","w") as file:
    file.write("I am learning Python!\n")

# 追加写入    
with open("text.txt","a") as file:
	file.write("\n")
    file.write("What I want to add on goes here")

猜你喜欢

转载自blog.csdn.net/qq_45100200/article/details/130787746