Python从文件中读取指定的行以及在文件指定位置写入

yipeiwu_com5年前Python基础

Python从文件中读取指定的行

如果想根据给出的行号, 从文本文件中读取一行数据,  Python标准库linecache模块非常适合这个任务:

测试文件内容 :

This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
This is line 6.
This is line 7.
This is line 8.

测试代码:

>>> import linecache
>>> file_path = r'D:\work\python\test.txt'
>>> line_number = 5
>>> def get_line_context(file_path, line_number):
...  return linecache.getline(file_path, line_number).strip()
...
>>> get_line_context(file_path, line_number)
'This is line 5.'
>>>

对于这个任务来说,标准的linecache模块是Python能够提供的最佳解决方案。

利用python在文件中的指定位置写入

import os 
file = open( "a.txt", "r" ) 
file_add = open("a.txt","r") 
content = file.read() 
content_add = file_add.read() 
pos = content.find( "buildTypes")
if pos != -1: 
  content = content[:pos] + content_add + content[pos:] 
  file = open( "a.txt", "w" ) 
  file.write( content ) 
  file.close() 
  file_add.close() 

与find用法相同的还有rfind方法,不同的是rfind方法是从文件末尾开始搜索。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

win8.1安装Python 2.7版环境图文详解

win8.1安装Python 2.7版环境图文详解

Python相信大家都有所耳闻,特别是Python进入山东省小学教材,还列入全国计算机等级考试。 打算爬网易云音乐评论的我,首先要安装一个Python环境。 目前Python有2.x版和...

python序列化与数据持久化实例详解

python序列化与数据持久化实例详解

本文实例讲述了python序列化与数据持久化。分享给大家供大家参考,具体如下: 数据持久化的方式有: 1.普通文件无格式写入:将数据直接写入到文件中 2.普通序列化写入:json,pic...

java直接调用python脚本的例子

java直接调用python脚本的例子

复制代码 代码如下:import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {...

Django添加KindEditor富文本编辑器的使用

KindEditor简介: KindEditor是一套开源的在线HTML编辑器,主要用于让用户在网站上获得所见即所得编辑效果,开发人员可以用KindEditor 把传统的多行文本输入框...

Python 遍历列表里面序号和值的方法(三种)

Python 遍历列表里面序号和值的方法(三种)

三种遍历列表里面序号和值的方法: 最近学习python这门语言,感觉到其对自己的工作效率有很大的提升,特在情人节这一天写下了这篇博客,下面废话不多说,直接贴代码 #!/usr/bin...