Home  >  Article  >  Backend Development  >  How to write python file operations on specified lines

How to write python file operations on specified lines

尚
Original
2019-06-29 14:38:324093browse

How to write python file operations on specified lines

常常在操作文件时我们只想在某一行的插入信息,可以先将文件读入列表中,利用列表的下标插入文本,之后再重新写入文件。

但是弊端是,如果文件量太大列表的性能可能不是很高。

python代码:

#coding=utf-8
lines=[]
f=open("d:\\1script\\1.txt",'r')  #your path!
for line in f:
    lines.append(line)
f.close()
print lines
lines.insert(3,"666\n")           #第四行插入666并回车
s=''.join(lines)
f=open("d:\\1script\\1.txt",'w+') #重新写入文件
f.write(s)
f.close()
del lines[:]                      #清空列表
print lines

更多Python相关技术文章,请访问Python教程栏目进行学习!

The above is the detailed content of How to write python file operations on specified lines. 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