Python example of inserting a line at the beginning of text

不言
Release: 2018-05-02 14:13:47
Original
3689 people have browsed it

This article mainly introduces the example of inserting a line at the beginning of the text in python. It has certain reference value. Now I share it with you. Friends in need can refer to the

question.

For a text file, you need to insert a line at the beginning, leaving the other contents unchanged

Solution

with open('article.txt', 'r+') as f:
 content = f.read()  
 f.seek(0, 0)
 f.write('writer:Fatsheep\n'+content)
Copy after login

The string 'writer:Fatsheep\n' is the content to be inserted.

Effect

After running the code:

Note

##f.seek(0, 0) is indispensable, file.seek(off, whence=0) moves the file pointer in the file, Offset from whence (0 represents the beginning of the file, 1 represents the current position, 2 represents the end of the file) offset by bytes

If there is no it, the result of running is:

Related recommendations:


Python method to extract specified location records after groupby grouping

The above is the detailed content of Python example of inserting a line at the beginning of text. 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