Python 在设定的行范围内读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24716001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading in a text file in a set line range
提问by user2061913
Is it possible to read in from a text file a set line range for example from line 20 to 52?
是否可以从文本文件中读取设定的行范围,例如从第 20 行到第 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
我查看了文档和在线示例,只能找到指定新行或其他内容的示例
采纳答案by Martijn Pieters
You can use itertools.islice()
on the file object and use iteration to read only specific lines:
您可以itertools.islice()
在文件对象上使用并使用迭代仅读取特定行:
import itertools
with open(file_to_save, "r") as text_file:
for line in itertools.islice(text_file, 19, 52):
# do something with line
would read lines 20 through to 52; Python uses 0-based indexing, so line 1 is numbered 0.
将阅读第 20 行到第 52 行;Python 使用基于 0 的索引,因此第 1 行编号为 0。
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.
使用文件对象作为迭代器为您提供了很大的灵活性;您可以通过调用next()
文件对象来读取额外的行,例如,在执行此操作时推进“指针”行。
When using the file as an iterable, don'tuse readline()
; the two techniques are not easily mixed.
将文件用作可迭代对象时,不要使用readline()
; 这两种技术不容易混合。
回答by ZenOfPython
You can do two things. You can use enumerate()
, and use an if
statement:
你可以做两件事。您可以使用enumerate()
, 并使用if
语句:
text_file = open(file_to_save, "r")
lines = []
for index, text in enumerate(text_file):
if 19 <= index <= 51:
lines.append(text)
Or instead, you can use readlines()
and then slice:
或者,您可以使用readlines()
然后切片:
text_file = open(file_to_save, "r")
lines = text_file.readlines()
lines = lines[19:52]
回答by python starter
HM,you can try something with while loop....but you should know up to which string you want text to be loaded,which is not best way:
嗯,您可以尝试使用 while 循环……但是您应该知道要加载哪个字符串,这不是最好的方法:
text_file=open(name,'r')
line=text.readline()
while line!=(" ") #type the line where you want it to stop
print (line