File30. Дан файл целых чисел, содержащий четное количество элементов. Удалить из данного файла вторую половину элементов.
Решение на Python 3:
# -*- coding: utf-8 -*-
import random
def GenerateNumbers(fname):
N = random.randint(1,10) * 2
print("N = ",N)
L = []
x = random.randrange(1,10)
L.append(x)
for i in range(1,N):
lst_rnd = list(range(1,10))
lst_rnd.remove(x)
x = random.choice(lst_rnd)
L.append(x)
print(L)
try:
f = open(fname, "w")
try:
for x in L:
line = str(x)+"\n"
f.write(line)
finally:
f.close()
except IOError:
print('Write error: ',fname)
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 = "file30_in.txt"
f_output = "file30_out.txt"
GenerateNumbers(f_input)
print("Read from:",f_input)
print("Write to:",f_output)
N = CountFile(f_input)
N = int(round(N/2.0))
try:
with open(f_input, 'r') as f_in, open(f_output, 'w') as f_out:
for i in range(N):
line = f_in.readline()
f_out.write(line)
except IOError:
print('Open error: ',file1)