This example describes 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 stored in the list to a file.
F=file ("Hello.txt", "w+")
li=["Hello world\n", "Hello china\n"]
f.writelines (LI)
f.close ()
Contents of the file:
Both the Write () and Writelines () methods erase the contents of the file before writing, and then write back to the new content, equivalent to the "overwrite" method. If you need to keep the contents of the file, you just need to append new content, you can use the "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 World
Hello
goodbye
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 World
Hello
Goodbyegoodbye
I hope this article will help you with your Python programming.