python- write to file

First, write an empty file (cover)

# coding=UTF-8
filename = 'test_text.txt'
with open(filename, 'w') as file_object:
    file_object.write("Add a word")

If you write to the file does not exist, open () will automatically create it

If the file already exists existing content, it is cleared and then write

 

Write multiple lines

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

 

 Line feed

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

 

 Second, add content in the original document

Use '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")

 

Guess you like

Origin www.cnblogs.com/erchun/p/11766408.html