[英]How to read a specific range of lines in an external file in python?
Lets say you have a python file with 50 lines of code in it, and you want to read a specific range lines into a list. 假设您有一个包含50行代码的python文件,并且想要将特定范围的行读入列表。 If you want to read ALL the lines in the file, you can just use the code from this answer :
如果您想读取文件中的所有行,则可以使用以下答案中的代码:
with open('yourfile.py') as f:
content = f.readlines()
print(content)
But what if you want to read a specific range of lines, like reading line 23-27? 但是,如果您想读取特定范围的行,例如读取23-27行,该怎么办?
I tried this, but it doesn't work: 我试过了,但是不起作用:
f.readlines(23:27)
You were close. 你近了
readlines
returns a list and you can slice that, but it's invalid syntax to try and pass the slice directly in the function call. readlines
返回一个列表,您可以对其进行切片,但是尝试直接在函数调用中传递切片是无效的语法。
f.readlines()[23:27]
If the file is very large, avoid the memory overhead of reading the entire file: 如果文件很大,请避免读取整个文件的内存开销:
start, stop = 23, 27
for i in range(start):
next(f)
content = []
for i in range(stop-start):
content.append(next(f))
尝试这个:
sublines = content[23:27]
If there are lots and lots of lines in your file, I believe you should consider using f.readline()
(without an s
) 27 times, and only save your lines starting wherever you want. 如果文件中有很多行,我相信您应该考虑使用
f.readline()
(不带s
)27次,并且只保存您想开始的行。 :) :)
Else, the other ones solution is what I would have done too (meaning : f.readlines()[23:28]
. 28, because as far as I remember, outer range is excluded. 否则,其他解决方案也是我也会做的(意味着:
f.readlines()[23:28]
。28),因为据我所知,外部范围已被排除在外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.