Text7. Дана строка S и текстовый файл. Добавить строку S в начало файла.

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

import random
import string

file1 = "text07.txt"

N = random.randrange(1,20)
S = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
print("String:",S)

content = ""
try:
with open(file1,'r') as f:
content = f.read()
except IOError:
print('Open error: ',file1)

print("Write string to ",file1)
try:
f = open(file1, "w")
try:
f.write(S+"\n")
finally:
f.close()
except IOError:
print('Write error: ',file1)

print("Append content to ",file1)
try:
f = open(file1, "a")
try:
f.write(content)
finally:
f.close()
except IOError:
print('Append error: ',file1)