The main problem here is probably that you are using simple strings that represent relative file paths. If you were to provide a full traceback, then I could give you a better answer.
Now, this will give you problems a lot of the times, and so it is best practice to always use absolute paths.
Now, what is an absolute path, you say? Well, its the path that goes all the way from your drive to your actual file destination. For example: C:/Foo/Bar/Cheese/happy.py
. A relative file path is a path relative to your current directory. For example you were in your command line and you were @ C:/Foo/Bar/Cheese/happy.py
, and if there was another file in the same directory, say more.py
, then you could reference it as ./more.py
, but this can lead to several problems as you are facing right now.
So, what is the solution? Like I said, use absolute paths, now how do you do this? Well you use a module called os
.
So, something like this:
import os
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "name_of_file_in_current_dir")).replace(os.pardir, "/")
Now let me tell you what this means, os.path.abspath
gives you an absolute path. os.path.join
allows you to join paths in a flexible ways, you can join folders. os.path.dirname
gives you the absolute path a specified file, in this case __file__
. __file__
is a special variable. Finally, internally an OS can use different ways to separate directories, some use //
, some use \
, some use \\
. Now, this is what works best /
, since it works on all systems. We use os.pardir
because it will work on all systems, Windows, Linux and Unix, which makes your code portable! :D
Also, a good recommendation would be using the with
statement. Like so:
with open(file_path) as file:
This is the same as putting a try/catch
block around it, but in once simple line. It also opens and closes the file stream for you.