erchun

一、写入空文件(覆盖)

# 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")

 

分类:

技术点:

相关文章:

  • 2021-11-02
  • 2021-12-18
  • 2021-05-20
  • 2021-06-18
  • 2021-09-03
  • 2021-07-31
  • 2021-05-13
  • 2021-08-16
猜你喜欢
  • 2021-08-16
  • 2021-11-05
  • 2021-08-16
  • 2021-09-07
  • 2021-11-12
  • 2021-09-17
相关资源
相似解决方案