How to append text to a file

anonymity
Release: 2019-05-25 09:47:16
Original
5107 people have browsed it

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?

How to append text to a file

1. The original way to open a file is:

 file = open(pathTxt, 'w', encoding='utf-8')
Copy after login

2. The modified way of writing: (Change the file opening mode from "write" Change to "Append")

 file = open(pathTxt, 'a', encoding='utf-8')
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template