How to write python file operations on specified lines

Release: 2019-07-08 09:17:21
Original
4116 people have browsed it

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
Copy after login

更多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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!