File27. Дан файл целых чисел с элементами \(A_1, A_2, ..., A_N\) (N — количество элементов в файле). Заменить исходное расположение его элементов на следующее:
\(A_1, A_N, A_2, A_{N-1}, A_3, ...\) .

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

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

def GenerateReals(fname):
#generate random real numbers and save them to file
N = random.randint(2,15)
N = 9
print("N = ",N)
L = []
x = round(random.uniform(0, 10),1)
L.append(x)
for i in range(1,N):
lst_rnd = [round(random.uniform(0, 10),1) for _ in range(0,10)]
try:
lst_rnd.remove(x)
except:
pass
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

def GetLineK(fname,K):
#count number of rows in given text-file
line = ""
N = 0
try:
with open(fname,'r') as f:
for line in f:
N += 1
if K == N:
break
except IOError:
print("Open error:",fname)
return -1
finally:
return line

file1 = "file27.txt"
GenerateReals(file1)
print("Read from:",file1)

try:
#file for temporary data
N = random.randrange(5,8)
S = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase \
+ string.digits) for _ in range(N))
temp_file_1 = "temp_" + S + "_1.txt"
temp_file_2 = "temp_" + S + "_2.txt"
#print()
print("Temp file 1:",temp_file_1)
print("Temp file 2:",temp_file_2)

N = CountFile(file1)
N1 = int(math.ceil(N/2))
N2 = N - int(N/2)

with open(file1, 'r') as f_in, open(temp_file_1, 'w') as f_out:
for i in range(1,N1+1):
line = f_in.readline()
print(i,":",line,end="")
f_out.write(line)

with open(temp_file_2, 'w') as f_out:
for i in range(N,N2,-1):
#print(i)
line = GetLineK(file1,i)
print(i,":",line,end="")
f_out.write(line)

with open(file1, 'w') as f_out, open(temp_file_1, 'r') as f_in1, \
open(temp_file_2, 'r') as f_in2:
for i in range(0,N2):
line = f_in1.readline()
f_out.write(line)
line = f_in2.readline()
f_out.write(line)

#sys.exit()

try:
os.remove(temp_file_1)
os.remove(temp_file_2)
except OSError as e:
print("\nError:", e)

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