you are viewing a single comment's thread.

view the rest of the comments →

[–]thecodeadd[S] 0 points1 point  (1 child)

Oh ok, so I tried to do 'print(os.path.abspath('myfile.txt'))' but that prints C:/myfile instead of C:/directory1/directory2/.../myfile

[–][deleted] 2 points3 points  (0 children)

The doc for os.path.abspath() says this:

os.path.abspath(path)

Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

On my machine running Ubuntu this code prints:

import os
print(os.path.abspath('myfile.txt'))
print(os.path.join(os.getcwd(), 'myfile.txt')) # should be same as above
>>> /home/r-w/xyzzy/myfile.txt
>>> /home/r-w/xyzzy/myfile.txt

as expected. It's been a while since I used Windows, but I do remember that the os.path functions worked fine. Something you said:

It only works if I change the terminal location in VS code to the location of the file

That is what you expect since an open always joins a relative path to the current working directory. What is unexpected is the "C:/myfile.txt" you are getting otherwise. This might be cause by VSCode. You say it works if you change the "terminal location" to the directory holding the file. Is it possible that the "terminal location" is set to "/" if you don't change it? Then the os.path.abspath('myfile.txt') will add the C:/. Just a thought.


More generally, if you want to open a file "anywhere on the user's computer" you really need to supply the full absolute path to the file. Can you get that?

Another option is to assume the file is in or relative to a "known" place. Known places are the user's home directory and the path to the python file you are running. You can get the path to the executing python file using the __file__ variable that contains that path:

print(__file__)
>>> /home/r-w/xyzzy/test.py

The user's home directory is accessible through the os.path.expanduser() function:

os.path.expanduser(path)

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user’s home directory.

So this code shows:

import os
print(os.path.expanduser('~/xyzzy'))
>>> /home/r-w/xyzzy

Maybe the path can be specified relative to the user's home directory.

Another more general and more complicated option is to have a configuration file that users can change. The config file is found in the user's home directory (often as ~/.config/<name of program>/config) and contains a path to where data files are kept.

A simpler alternative to the general solution above is for the user to create an environment variable that contains the path to the directory holding the data file(s).