The python file is written to the instance analysis
- 2020-05-07 19:56:11
- OfStack
This article illustrates the use of writing to an python file. Share with you for your reference. Specific analysis is as follows:
The wirte() method in Python writes the string to a file, and the writelines() method writes the contents of 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 document:
hello world
hello china
The write() and writelines() methods clean up the original contents of the file before they are written, and then re-write the new contents. If you need to keep the original contents of the file, but just append new contents, you can open the file in "a+" mode.
f=file("hello.txt","a+")
new_context="goodbye"
f.write(new_content)
f.close()
At this point the contents of hello.txt are as follows:
hello world
hello china
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 china
goodbyegoodbye
I hope this article has been helpful to your Python programming.