Home  >  Article  >  Backend Development  >  Python implements the method of appending text to a specified line in txt

Python implements the method of appending text to a specified line in txt

不言
不言Original
2018-05-02 16:09:119869browse

This article mainly introduces the method of appending text to a specified line in txt in python. It has a certain reference value. Now I share it with you. Friends in need can refer to it

As shown below:

fp = file('data.txt')
lines = []
for line in fp: 
  lines.append(line)
fp.close()
 
lines.insert(1, 'a new line') # 在第二行插入
s = '\n'.join(lines)
fp = file('data.txt', 'w')
fp.write(s)
fp.close()

Related recommendations:

Python implements the generation of strips for images in files Labeled txt file method

Python method to merge all txt files in the same folder

##

The above is the detailed content of Python implements the method of appending text to a specified line in txt. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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