H
H
Hacker29612021-06-28 09:59:49
Python
Hacker2961, 2021-06-28 09:59:49

FileNotFoundError: [Errno 2] No such file or directory: 'config.txt', how to fix?

I am writing a bot in python, and I need its token to be read from a file located in the same directory (there are two files in the bot folder - python script and config.txt)
When I run it, I get an error saying that such a file was not found , although it is:

FileNotFoundError: [Errno 2] No such file or directory: 'config.txt'

I tried to put /, //, \, \\ - does not help
the OS - Win 7
How to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-06-28
@Hacker2961

Your path is relative. Therefore, it is considered relative to the current working directory. This directory may or may not be the same as the directory where the script is located!
Therefore, the best way is to calculate the path yourself.
sys.argv[0] always points to the path to the script file.
Therefore, you can do either this (using os.path):

os.path.join(os.path.dirname(sys.argv[0]), 'config.txt')

either like this (using pathlib)
pathlib.Path(sys.argv[0]).parent / 'config.txt'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question