Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"No such file or directory" when files are in the same directory

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?

like image 389
user3689303 Avatar asked Sep 02 '25 05:09

user3689303


1 Answers

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.)

like image 169
Greg Hewgill Avatar answered Sep 04 '25 17:09

Greg Hewgill