简体   繁体   中英

Getting error with python open() function

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:

  • you're sure the file does exist (the r+ mode can't read it otherwise), and
  • you (or a library) doesn't use os.chdir() to change the working directory

then you could

  • if you run your app via PyCharm (or some other IDE), your working directory is set wrong; see your PyCharm/IDE settings to set it correctly in the launch configuration.
  • if you run via the command line, ensure you're in the directory where users.txt is when you do run your app

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM