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)
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 bytesIf 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!