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()

2 番目のタイプは 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