Text15. Дано целое число K и текстовый файл. Удалить из файла строку с номером K. Если строки с таким номером нет, то оставить файл без изменений.

Решение на Python 3:

# -*- coding: utf-8 -*-
import random
import shutil
import string
import os

file1 = "text15.txt"
print("Read from:",file1)

K = random.randrange(1,20)
#K = 17
print("K = ",K)
n = 0
try:
with open(file1, 'r') as infile:
for line in infile:
n += 1
print("n = ",n)

if K <= n:
#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("Temp file:",temp_file)

shutil.copyfile(file1, temp_file)

n = 0
with open(file1, 'w') as outfile, open(temp_file, 'r') as infile:
for line in infile:
n += 1
print(n,":",line,end="")
if n != K:
outfile.write(line)

try:
os.remove(temp_file)
except OSError as e:
print("Error:", e)

except IOError:
print('Open error: ',file1)