例如:
print(readLines('B:\input.txt', 0, 3)) //0 and 3 are start and end indexes
会变成:
print(readLines('B:\input.txt', 0:3))
任何帮助表示赞赏
答案 0 :(得分:0)
您可以通过将参数转换为字符串来使其工作:
print(readLines('B:\input.txt', "0:3"))
然后在函数中解压缩:
def readLines(text, index):
start, stop = index.split(':')
答案 1 :(得分:0)
您可以使用itertools.islice:
from itertools import islice
def read_lines(it,start,stop):
return list(islice(it,start, stop))
print(read_lines([1,2,3,4,5,6],0,3))
[1, 2, 3]
在档案中:
from itertools import islice
def read_lines(f, start, stop):
with open(f) as f:
return list(islice(f, start, stop))
如果您只想使用字符串输出return " ".join(islice(f, start, stop))
如果你想在线上工作,只需迭代islice对象:
def read_lines(f, start, stop):
with open(f) as f:
for line in islice(f, start, stop):
do stuff