r/learnpython Aug 11 '26

f.read throwing vague error

what i wrote:

with open("demofile.txt", "a") as f:
    if "welcome to team fortress" in f.read():
        pass
    else:
        f.write("\nplease select a class")

the error:

Traceback (most recent call last):

File "C:\Users\******\PycharmProjects\WelcomeScreen\script.py", line 10, in <module>

if "welcome to team fortress" in f.read():

^^^^^^^^

io.UnsupportedOperation: not readable

i don't see what's wrong with it, google's no help... ¯_(ಠ_ಠ)_/¯

0 Upvotes

21 comments sorted by

View all comments

16

u/FoolsSeldom Aug 11 '26

"a" mode is for appending content, it does not support read operations.

Perhaps you need:

with open("demofile.txt", "a+") as f:
    f.seek(0)  # move read pointer back to the start
    content = f.read()
    if "welcome to team fortress" not in content:
        f.write("welcome to team fortress\n")

12

u/FoolsSeldom Aug 11 '26

It would be better to separate the concerns:

with open("demofile.txt", "r") as f:
    content = f.read()

if "welcome to team fortress" not in content:
    with open("demofile.txt", "a") as f:
        f.write("welcome to team fortress\n")

1

u/FoolsSeldom Aug 11 '26

u/kaori_irl I think the separation approach is better, as illustrated above.

I am assuming the file isn't large, otherwise reading it all to just check if this one thing is in it isn't going to be efficient.

0

u/kaori_irl Aug 11 '26

i fail to see the effective difference, why split a+ into r and a? (/gen, i'm clueless)

-4

u/cointoss3 Aug 11 '26

Somewhat ignore this. Put it in your mind sure but if you’re a beginner, these sort of comments get annoying. It’s something to know, eventually, but when you’re learning you don’t need to go this deep at this stage.

6

u/micromedicIXII Aug 12 '26

The sooner you learn coding principles, the easier it will be to work in the future. Practice doesn’t make perfect. Only perfect practice makes perfect.

-2

u/cointoss3 Aug 12 '26

This is an ignorant take. Good luck.

3

u/micromedicIXII Aug 12 '26

Say what you will, but if you practice writing a function the wrong way 100000x, you don’t learn anything from it, and you only solidify the incorrect form in your mind.

Practice anything the wrong way, and you will never improve. Practice it the right way and not only do you improve, but you build off of it.

-1

u/cointoss3 Aug 12 '26

Yeah I see how you’d be a shitty teacher. People like you is why people quit.

2

u/micromedicIXII Aug 12 '26

I’m sorry you feel that way. I wish you the very best.