Python writes data that can be appended and multiple data to the local txt file

The first one is opened between open, but in the end it needs to be closed with .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()

The second type is opened with with, and does not need to be closed with the .close() operation, it will be closed automatically.

# 覆盖写入
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")

Guess you like

Origin blog.csdn.net/qq_45100200/article/details/130787746