S
S
Stanislav Semerkov2020-07-22 21:41:34
Python
Stanislav Semerkov, 2020-07-22 21:41:34

Working with files in Python An error occurs while reading the file. What is the reason?

Hello. I can not understand. Simple code :

with open('textfile_2.txt', 'tw', encoding='utf-8') as f1:
    f1.write("Привет русский текст")
    f1.read()

An error pops up:
Traceback (most recent call last):
  File "Диск:/Lessons/python-projects/book1/files/ИМЯ ФАЙЛА.py", line 69, in <module>
    f1.read()
io.UnsupportedOperation: not readable

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
soremix, 2020-07-22
@SegunPosad

Set file open mode to read

G
gorodnev, 2020-07-22
@gorodnev

It confuses me a little that you open the flag for writing 'w', and then you try to read something on it. There are two ways out - either reopen the file for reading-writing, or refuse one of the operations.
PS: after a little thought, I came up with the idea that you are reprinting some kind of listing. And there the mode is not 'tw', but 'rw' (t and r are adjacent letters in the layout). And 'rw' is just the "read-write" mode.

S
Stanislav Semerkov, 2020-07-24
@SegunPosad

Thank you. He fooled himself. Everything worked.
with open('text_1', 'r', encoding='utf-8') as f1:
print(f1.read())
or
f = open('text_1', encoding='utf-8')
print(f .read())
f.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question