Text11. Дан текстовый файл. Продублировать в нем все пустые строки.
Решение на Python 3:
import random
import string
import os
import sys
#file for reading and adding empty row
file1 = "text11.txt"
#file for temporary data
N = random.randrange(5,8)
S = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
temp_file = "temp_" + S + ".txt"
print("Temp file:",temp_file)
print("Write to:",temp_file)
try:
f_temp = open(temp_file, "w")
try:
try:
with open(file1,'r') as f_open:
for line in f_open:
f_temp.write(line)
if line.strip("\n") == "":
f_temp.write(line)
except IOError:
print("Read error:",file1)
finally:
f_temp.close()
except IOError:
print('Write error: ',file1)
print("Rename {0} to {1}".format(temp_file,file1))
try:
os.rename(temp_file, file1)
except WindowsError:
os.remove(file1)
os.rename(temp_file, file1)
except OSError as e:
print("Error:", e)