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 GenerateInts(fname):
#generate random real numbers and save them to file
N = random.randint(2,15)
N = 9
#N = 10
print("N = ",N)
try:
f = open(fname, "w")
try:
for i in range(0,N):
#x = random.randint(1,11)
x = i + 1
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):
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"
GenerateInts(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 = "temp27_" + S + "_1.txt"
temp_file_2 = "temp27_" + 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)
try:
f_in = open(file1, 'r')
try:
print("===== Part 1 =====")
f_out = open(temp_file_1, 'w')
for i in range(1,N1+1):
line = f_in.readline()
print(i,":",line,end="")
f_out.write(line)
except IOError:
print('Read Error: ',temp_file_1)
finally:
f_out.close()
try:
print("===== Part 2 =====")
f_out = open(temp_file_2, 'w')
for i in range(N,N2,-1):
#print(i)
line = GetLineK(file1,i)
print(i,":",line,end="")
f_out.write(line)
except IOError:
print('Read Error: ',temp_file_2)
finally:
f_out.close()
except IOError:
print('Read Error: ',file1)
finally:
f_in.close()
try:
f_out = open(file1, 'w')
try:
f_in1 = open(temp_file_1, 'r')
f_in2 = open(temp_file_2, 'r')
for i in range(0,N2):
line = f_in1.readline()
f_out.write(line)
line = f_in2.readline()
f_out.write(line)
finally:
f_in2.close()
f_in1.close()
f_out.close()
except IOError:
print('Write Error: ',file1)
try:
os.remove(temp_file_1)
os.remove(temp_file_2)
except OSError as e:
print("\nError:", e)
except IOError:
print('Open error: ',file1)