Text10. Дано целое число K и текстовый файл. Вставить пустую строку после строки файла с номером K. Если строки с таким номером нет, то оставить файл без изменений.
Решение на Python 3:
import random
import string
import os
import sys
def CountF(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
#file for reading and adding empty row
file1 = "text10.txt"
K = random.randrange(1,20)
print("Adding empty row before row #",K)
N = CountF(file1)
if N < K:
print("File {0} has less then {1} rows".format(file1,K))
sys.exit()
#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:
N = 0
try:
with open(file1,'r') as f_open:
for line in f_open:
if N == K:
f_temp.write("\n")
f_temp.write(line)
N += 1
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)