添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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")

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.Thi...
python 在txt文本 指定 符号前面 插入 指定 字符 本文主要实现,在txt文本的“((” 位置 前面,插入字符串‘POLYGON’;keyword为需要查找的 指定 符号,str为需要插入的字符串,当然这些都可以根据自己的需要进 修改。content[:post]指的是 指定 符号前面的所有的字符,content[post:] 指定 符号后面所有的字符。 代码比较简单,大家直接加载测试即可。 file = open(r"D:\20200309\shujushouji\geopandas4\shp\data004.txt"
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
日常工具搬运—— python 写入 txt 文件 同样,也是代码里的一个小需求,但是一时半会不知道怎么解决。需求是有一个大列表 list = [ [ a , …, z], … , [w, …, v]],需要把列表 的每一个子列表逐 写入 到txt 文件 。乍一看这个功能很好实现,但是网上搜了几个都不能实现逐 写入 ,而是一股脑都写进去了,没有换 (加了换 符也没用),最后阴差阳错用下面的方法解决了。 同样,仅作为自己的学习笔记,若有不对之处请多多指正。 先来看一下原来的列表数据: 下面展示一些 内联代码片。 以上代码 ,首先打开 文件 并以读写模式打开它。随后,移动 文件 指针到 指定 位置 (例如,第10个字符)并向该 位置 写入 新的字符串。 如果要删除文本 文件 的某一 ,则可以使用以下示例代码: ``` python # 打开 文件 file = open("file.txt", "r") # 读取 文件 内容 contents = file.readlines() # 关闭 文件 file.close() # 删除第2 内容 del contents[1] # 打开 文件 写入 模式 file = open("file.txt", "w") # 写入 新的内容 for line in contents: file.write(line) # 关闭 文件 file.close() 以上代码 ,首先以只读模式打开 文件 读取 文件 内容。随后, 从文件 内容 删除第二 (即索引为1的 )。最后,以 写入 模式打开 文件 写入 新的内容,即已删除 指定 文件 内容。