0

This is my code:

import os
...
    savepath = "/home/myname/Documents/programfolder/vanities/"
    #ctx.author.id is from the discord.py module, not relevant to question.
    userFile = os.path.join(savepath, str(ctx.author.id) + ".txt")
    ...
    try:
            vanity = open(userFile, "r")
            vanity = vanity.read()
            server = get_guild(myserverid)
            vanityrole = server.get_role(vanity)
            vanityrole = role.edit(name = str(rolename), colour = int(hexcolour))
    except FileNotFoundError:
            vanity = open(userFile, "w")
            vanityrole = role_create(name = str(rolename), colour = int(hexcolour))
            vanity = vanity.write(str(vanityrole.id))
            pass

When I run this, I receive an error

Ignoring exception in command vanity:
Traceback (most recent call last):
  File "./bot.py", line 27, in vanity
    vanity = open(userFile, "r")
FileNotFoundError: [Errno 2] No such file or directory: '/home/myname/Documents/programfolder/vanities/myid.txt'

Why does the try: except FileNotFoundError: not work? I tried it with except IOError and OSError and neither worked. The error also occurs with open(userFile, "w"). For reference, my program runs in /home/myname/Documents/programfolder/

Syz_01
  • 13
  • 6

1 Answers1

0

Check if savepath exists.

The with clause takes care of closing resources, in most cases. You can wrap something like this in a try/catch, or check first if the directory doesn't exist (first link above) and then create if needed.

# handle directory existence first, here
...
with open(userFile, 'a+') as fp:
    fp.seek(0)
    contents = fp.read()
    # handle contents if found, here
    if not contents:
        newContents = ...
        fp.write(newContents)
ELinda
  • 2,223
  • 1
  • 7
  • 7