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:workpythontest.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_a

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....
python 读取 文件 指定 ,可以使用以下的方法 1、os.mknod(“test.txt”) #创建空 文件 2、fp = open(“test.txt”,w) #直接打开一个 文件 ,如果 文件 不存在则创建 文件 3、open 模式 处理 文件 时,一个常见的需求就是 读取 文件 指定 内容,那么该如何实现的? with open('a.log', 'r') as fp: lines = fp.readlines() last_line = lines[-1] 即使不考虑异常处理的问题,这个代码也不
file.read([size]) 其 ,file 表示已打开的 文件 对象;size 作为一个可选参数,用于 指定 一次最多可 读取 的字符(字节)个数,如果省略,则默认一次性 读取 所有内容。 readline() 方法每次 读取 内容,一般不太用 readlines() 方法一次性 读取 整个 文件 内容,并按 返回到 list 。 for line in fileinput.input('data.txt', inplace=2): if line.startswith('foo1'): processing_foo1s = True else: if processing_foo1s: