Both files, the .py file and a .txt file it calls with
champions_list = open('champions.txt','rU').read().split('\n')
are in the file folder C:\Users\[My Name]\Programming\[file name]
.
I'm calling the .py file through Command prompt and it returns the error
IOError: [Errno 2] No such file or directory: champions.txt
Has this happened to anyone else before?
When you open a file with open('champions.txt')
, then the OS expects to find the champions.txt
file in the current directory. The current directory is the directory of the command prompt window where you started the program. This is not (necessarily) the same as the directory where the Python script is stored.
You may be able to fix this by doing:
import os
import sys
open(os.path.join(os.path.dirname(sys.argv[0]), 'champions.txt')
This takes the full name of the script in sys.argv[0]
, takes the directory part, and then joins that to the file name you want. This will open the file in the script directory, not the current directory.
(Note that using sys.argv[0]
in this way is OS-dependent, and works on Windows but may not work the same way on other systems.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With