Text21. Дан текстовый файл, содержащий более трех строк. Удалить из него последние три строки.

Решение на Python 3:

import random
from collections import deque

q = deque([])

f_input = "text21_in.txt"
f_output = "text21_out.txt"
#GenerateNumbers(f_input)
print("Read from:",f_input)
print("Write to:",f_output)

K = 3
N = random.randrange(K,15)
print("K = ",K)
print("N = ",N)
print("code of 'a' ", ord('a'))
try:
f = open(f_input, "w")
try:
s = ''
for i in range(N):
s += chr(ord('a') + i)
#print(s)
f.write(s + "\n")
finally:
f.close()
except IOError:
print('Файл не создан')

try:
with open(f_input, 'r') as f_in, open(f_output, 'w') as f_out:
for i in range(K):
line = f_in.readline()
q.append(line)
#print(q)
for line in f_in:
q.append(line)
line = q[0]
f_out.write(line)
q.popleft()
#print(q)

except IOError:
print('Open error: ',file1)