2 回答
TA贡献1789条经验 获得超8个赞
首先,您只能得到n带有的第一行itertools.islice,然后写下这些行:
from itertools import islice
n = 10
with open('a.txt', 'r') as infile, open('b.txt', 'w') as outfile:
first_lines = islice(infile, n)
outfile.writelines(first_lines)
TA贡献1776条经验 获得超12个赞
我从Read large text files in Python, line by line without loading it in memory的接受答案中抓住了这个:
with open("log.txt") as infile:
for line in infile:
do_something_with(line)
现在,适用于您的具体问题:
def grab_lines(in_path, out_path, start, end):
with open(out_path, "w") as outfile:
counter = -1
with open(in_path) as infile:
for line in infile:
counter += 1
if counter < start:
continue
elif start <= counter <= end:
outfile.write(line)
else:
return
希望这可以帮助!
添加回答
举报