-1

I've been working on this Python project and just realized there's an issue. At first I thought it was just in Linux because I tried to create a command to open the file in the file path and then realized when it's ran anytime outside of the destination folder that it runs an error even in Windows. So it has to be an issue with my code in general. Basically I'm trying to call the program to read and print data from a text file.

help_text = open("files/help_text.txt","r") 
help_text_content = help_text.read()
print(help_text_content)

All I want to do is make sure that it reads the file no matter where the .py file is located. I can't do C:\Location because if the user installs the file it might be located somewhere else. So I need an absolute location reader that knows where the file itself is.

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Is the `txt` file always at the same location compared to location of the `py` file? e.g. subfolder `files` in the folder where the `py` file is? I think the problem comes from running the script from different CWD than the one where the script is. – buran Jun 21 '21 at 07:47
  • So the Python file and the text file might be located anywhere? In that case you need external configuration. You might want to take a look at [python-dotenv](https://pypi.org/project/python-dotenv/) for trivial configuration file reading. – Taxel Jun 21 '21 at 07:47
  • @buran Yes it's always located in files/ which is always paired with the .py file – Russ Steighler Jun 21 '21 at 07:50
  • @RussSteighler I've updated my answer to include a lookup relative to the currently running script. – chthonicdaemon Jun 21 '21 at 07:53
  • You must devise some way to determine the location of the file. This is can done in different ways: 1. relative to the location of the `.py` script. Stored in a config file, or define in an environment variable with a certain name. On Windows you can also store information in the system registry, but that not portable. There are function in the [`os.path`](https://docs.python.org/3/library/os.path.html#module-os.path) module to convert relative paths into absolute if necessary. – martineau Jun 21 '21 at 07:53
  • Does this answer your question? [How do I get the full path of the current file's directory?](https://stackoverflow.com/questions/3430372/how-do-i-get-the-full-path-of-the-current-files-directory) – Tomerikoo Jun 21 '21 at 08:12

3 Answers3

1

The best way to handle file paths in Python is by using pathlib. This makes sure to handle all the details of using the right separators for paths and so on. I would use code like this:

import pathlib

# path of the current script:
parent = pathlib.Path(__file__).parent

help_file = parent / 'files' / 'help_text.txt'

# note: you can check that this file exists
if not help_file.is_file():
    raise FileNotFoundError('Help file not found')

with help_file.open() as f:
    help_text_content = f.read()

print(help_text_content)
chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
  • Okay so at first I thought it worked, bc I didn't get an error as soon as starting the program from outside the folder path. But now i'm getting this error. with help_file.open() as f: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1242, in open return io.open(self, mode, buffering, encoding, errors, newline, File "C:\Python_Path\pathlib.py", line 1110, in _opener return self._accessor.open(self, flags, mode) FileNotFoundError: [Errno 2] No such file or directory: 'files\\help_text.txt' – Russ Steighler Jun 21 '21 at 08:01
  • I think it's because it's adding a double backslash in files\\help_text.txt so not sure why that's happening – Russ Steighler Jun 21 '21 at 08:01
  • Okay i'll try the updated version and maybe that'll work – Russ Steighler Jun 21 '21 at 08:02
  • @RussSteighler that "double backslash" is just Python showing an escaped backslash in the string. I think the current version should correctly pick up the location of the actual .py file which is running. – chthonicdaemon Jun 21 '21 at 08:10
  • IT WORKED. Thank you so much. I had tried other answers before writing this one and tried the whole __file__ and pathlib and even os and nothing worked. Been trying to figure it out for days. Thank you – Russ Steighler Jun 21 '21 at 08:21
0

I am thinking that probably using the os module could help you get the current working directory file, and then you could just append the help_text.txt to get the location:

import os
current_dir = os.getcwd()
# /C:/User/
path= os.path.join(current_dir, "help_text.txt")
# /C:/User/help_text.txt
0

Based on the information provided in the comments (txt file is always located in files/ which is always paired with the .py file) - you need to get the location of the py file. Note, it may be (and in case of this error obviously it is) different from the current working directory from which you execute the py script. For extended discussion see How do I get the path and name of the file that is currently executing?

Then you need to concatenate the path of the py file and "files/help_text.txt". Of course you can use both os module or (better) pathlib module from standard library.

buran
  • 13,682
  • 10
  • 36
  • 61