The examples in this article describe the use of Python file writes. Share to everyone for your reference. The specific analysis is as follows:
The Wirte () method in Python writes a string to a file, and the Writelines () method writes the contents of the list to the file.
F=file ("Hello.txt", "w+") li=["Hello world\n", "Hello china\n"]f.writelines (LI) f.close ()
The contents of the file:
Hello Worldhello China
Both write () and Writelines () methods erase the contents of the file before writing, and then re-write the new content, which is equivalent to the "overwrite" method. If you need to keep the contents of the file, just need to append new content, you can use "A +" mode to open the file.
F=file ("Hello.txt", "A +") new_context= "Goodbye" F.write (new_content) f.close ()
The contents of this hello.txt are as follows:
Hello Worldhello Chinagoodbye
Practice:
>>> f=file ("Hello.txt", "w+") >>> li=["Hello world\n", "Hello china\n"]>>> f.writelines (LI) >>> f.close () >>> >>> f=file ("Hello.txt", "A +") >>> new_context= "Goodbye" >> > F.write (new_content) >>> f.write (new_content) >>> f.close ()
Results:
Hello Worldhello Chinagoodbyegoodbye
Hopefully this article will help you with Python programming.