File31. Дан файл целых чисел, содержащий более 50 элементов. Уменьшить его размер до 50 элементов, удалив из файла необходимое количество начальных элементов.
Решение на Python 3:
# -*- coding: utf-8 -*-
import random
import sys
def GenerateNumbers(fname):
N = random.randint(50,70)
print("N = ",N)
try:
f = open(fname, "w")
for i in range(0,N):
#x = random.randrange(1,10)
x = i + 1
line = str(x)+"\n"
f.write(line)
f.close()
except:
print("Error: ", sys.exc_info()[0])
def CountFile(fname):
#count number of rows in given text-file
N = 0
try:
with open(fname,'r') as f:
for line in f:
N += 1
#print(N,":",line)
except IOError:
print("Open error:",fname)
return -1
finally:
return N
f_input = "file31_in.txt"
f_output = "file31_out.txt"
GenerateNumbers(f_input)
print("Read from:",f_input)
print("Write to:",f_output)
try:
num_items = CountFile(f_input)
if num_items <= 50:
print("File must contain more than 50 items")
sys.exit()
num_extra = num_items - 50
with open(f_input, 'r') as f_in, open(f_output, 'w') as f_out:
for i in range(num_extra):
line = f_in.readline()
for i in range(50):
line = f_in.readline()
f_out.write(line)
except:
print("Error: ", sys.exc_info())