File35. Дан файл целых чисел, содержащий менее 50 элементов. Увеличить его размер до 50 элементов, записав в начало файла необходимое количество нулей.

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

# -*- coding: utf-8 -*-
import random
import sys
import os

def GenerateNumbers(fname):
N = random.randint(30,50)
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 = "file35_in.txt"
f_output = "file35_out.txt"
GenerateNumbers(f_input)
print("Read from:",f_input)
print("Write to:",f_output)

try:
N = CountFile(f_input)
print("N:",N)
K = 50 - N
print("K:",K)

with open(f_input, 'r') as f_in, open(f_output, 'w') as f_out:
for i in range(K):
f_out.write(str(i+1)+"\n")
for line in f_in:
f_out.write(line)

except:
print("Error: ", sys.exc_info())