This article mainly introduces the usage of writing python files. The example analyzes the usage skills of writing Python files, which is of great practical value, for more information about how to write python files, see the example in this article. 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.