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)
現(xiàn)在,適用于您的具體問題:
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
希望這可以幫助!
添加回答
舉報