Python file write instance analysis,
This article describes how to write python files. Share it with you for your reference. The specific analysis is as follows:
In Python, The wirte () method writes a string to a file. The writelines () method can write the content stored in the list to a file.
f=file("hello.txt","w+")li=["hello world\n","hello china\n"]f.writelines(li)f.close()
File Content:
hello worldhello china
The write () and writelines () Methods clear the original content of the file before writing, and then re-write the new content, which is equivalent to the "Overwrite" method. To retain the original content of the file, 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 content in hello.txt is 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()
Result:
hello worldhello chinagoodbyegoodbye
I hope this article will help you with Python programming.