The Wirte () method writes the string to a file, and the Writelines () method writes the contents stored in the list to the file.
F=file ("Hello.txt", "w+")
li=["Hello world\n", "Hello china\n"]
F.writelines (LI)
F.close ()
Contents of the file:
Hello World
Hello
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 original file, you just need to append new content, you can use the "A +" mode
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