File41. Дан файл целых чисел. Заменить в нем каждое положительное число на три нуля.
Решение на Python 3:
# -*- coding: utf-8 -*-
import random
import sys
import os
def GenerateNumbers(fname):
N = random.randint(0,20)
print("N = ",N)
try:
f = open(fname, "w")
for i in range(0,N):
x = random.randrange(-9,10)
#x = i + 1
line = str(x)+"\n"
f.write(line)
f.close()
except:
print("Error: ", sys.exc_info()[0])
f_input = "file41_in.txt"
f_output = "file41_out.txt"
GenerateNumbers(f_input)
print("Read from:",f_input)
print("Write to:",f_output)
try:
with open(f_input, 'r') as f_in, open(f_output, 'w') as f_out:
for line in f_in:
x = int(line)
if x > 0 :
f_out.write("0\n0\n0\n")
else:
f_out.write(line)
except:
print("Error: ", sys.exc_info())