I'm currently working on a discord bot and part of my project involves extracting data from a.txt file. It's in the same workspace as the bot, and when I open it from other modules in the workspace it works fine; however, when I call it from the bot client's.py file, I get this error:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\canon\Anaconda3\envs\tony\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:/Users/canon/PycharmProjects/discordia/bot.py", line 25, in on_message
x = dt.retrieve_account(user)
File "C:\Users\canon\PycharmProjects\discordia\discord_tools.py", line 25, in retrieve_account
user_file = open(txt_file, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'users.txt'
TLDR; calling open("users.txt", "r+")
from discord_tools.py works fine, but calling it from bot.py (which in turn references discord_tools.py) does not work.
Please help!
-geisha
Relative paths to open()
are relative to the process's working directory.
Assuming:
r+
mode can't read it otherwise), andos.chdir()
to change the working directorythen you could
Preferably, though, don't use relative paths; you can easily compute an absolute path no matter your working directory.
Eg in discordia/discord_tools.py
,
import os
discordia_path = os.path.dirname(__file__)
users_file_path = os.path.join(discordia_path, "users.txt")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.