When using python to crawl content from the website and save it to a local txt file, I found that each write overwrites the original content in the txt file. So how can I continue on the original basis? What about adding content to it?
1. The original way to open a file is:
file = open(pathTxt, 'w', encoding='utf-8')
2. The modified way of writing: (Change the file opening mode from "write" Change to "Append")
file = open(pathTxt, 'a', encoding='utf-8')
Description of mode parameters:
r: Open the file in read-only mode. The file pointer will be placed at the beginning of the file. This is the default mode.
r: Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
w: Open a file for writing only. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
w: Open a file for reading and writing. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
a: Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing.
a: Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be opened in append mode. If the file does not exist, a new file is created for reading and writing.
The above is the detailed content of How to append text to a file. For more information, please follow other related articles on the PHP Chinese website!