在设定的行范围内读取文本文件 [英] Reading in a text file in a set line range

查看:56
本文介绍了在设定的行范围内读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从文本文件中读取设置的行范围,例如从第20行到第52行?

Is it possible to read in from a text file a set line range for example from line 20 to 52?

我正在打开文件并像这样读取文件:

I am opening the file and reading the file like this:

text_file = open(file_to_save, "r")
line = text_file.readline()

但只想将数据保存在设定的范围内,或者如果可能的话,可以从包含---数据---的一行后到包含-数据结尾-的另一行中读入

but only want to save the data in a set range or if it possible to read in from a after a line containing --- data --- to another line containing -- end of data --

我已经浏览了文档和在线示例,只能找到指定换行符或其他内容的示例

I have looked through the documentation and online examples and can only find examples that specify a new line or something

推荐答案

您可以使用

You can use itertools.islice() on the file object and use iteration to read only specific lines:

import itertools

with open(file_to_save, "r") as text_file:
    for line in itertools.islice(text_file, 19, 52):
         # do something with line

将读取第20行到第52行; Python使用基于0的索引,因此第1行的编号为0.

would read lines 20 through to 52; Python uses 0-based indexing, so line 1 is numbered 0.

使用文件对象作为迭代器可以为您带来很大的灵活性;您可以通过在文件对象上调用next() 来阅读更多行,例如,在执行此操作时将指针"行推进.

Using the file object as an iterator gives you a lot of flexibility; you can read extra lines by calling next() on the file object, for example, advancing the line 'pointer' as you do so.

以可迭代方式使用文件时, 不要使用readline() ;这两种技术不容易混用.

When using the file as an iterable, don't use readline(); the two techniques are not easily mixed.

这篇关于在设定的行范围内读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆