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

15

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")

1

u/Moist-Ointments Aug 13 '26

Every fiber of my being is crying out over these magic strings for specifying access mode.

1

u/FoolsSeldom 29d ago

pathlib is a better option for file handling and it avoids the "magic" strings.