Python은 추가할 수 있는 데이터와 여러 데이터를 로컬 txt 파일에 씁니다.

첫 번째는 열기 사이에 열리지만 결국 .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