File25. Дан файл вещественных чисел. Заменить в нем все элементы на их квадраты.
Решение на Python 3:
# -*- coding: utf-8 -*-
import random
import string
import os
import sys
def GenerateReals(fname):
N = random.randint(2,15)
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)
file1 = "file25.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 = "temp_" + S + ".txt"
#print()
print("Temp file:",temp_file)
with open(file1, 'r') as f_in, open(temp_file, 'w') as f_out:
for line in f_in:
x = float(line.strip())
y = x * x
print("%1.1f : %2.2f" % (x, y))
#print(x,":",y)
s = str("%2.2f" % y)+'\n'
f_out.write(s)
#sys.exit()
with open(file1, 'w') as f_out, open(temp_file, 'r') as f_in:
for line in f_in:
f_out.write(line)
try:
os.remove(temp_file)
except OSError as e:
print("\nError:", e)
except IOError:
print('Open error: ',file1)