Home > Article > Backend Development > Python implements the method of appending text to a specified line in txt
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!