0

I am using filename = os.environ.get('HIRES_2023_FILE') to get a filename. The file is located in the directory of the python executable and I want it always to reside there as the executable will be distributed to different machines/locations.

If I set the environment variable to HIRES_2023_FILE = 2023_hires.csv it can't find it. If I set it to .\HIRES_2023_FILE = 2023_hires.csv it's read as .\\2023_hires.csv. I've tried using str.replace to no avail, it strips both \\.

Can anyone tell me how I can convert that into a correct filename so my open reads the file?

Jim Rutter
  • 45
  • 4
  • This is on a Windows machine by the way. – Jim Rutter Jun 21 '23 at 15:26
  • You should require that they set it to an absolute pathname. Otherwise it will be interpreted relative to their current working directory. Or you could assume that it's relative to their home directory. See https://stackoverflow.com/questions/4028904/what-is-a-cross-platform-way-to-get-the-home-directory for how to get their homedir. – Barmar Jun 21 '23 at 16:17
  • I ended up going this route; seems to be much safer and reliable. Thanks. – Jim Rutter Jun 21 '23 at 16:47

1 Answers1

0

Try using pathlib to manipulate paths docs. It abstracts away a lot of pain that arises when trying to do string path manipulation.

filename = pathlib.WindowsPath(os.environ.get('HIRES_2023_FILE'))

  • Thanks. That worked great locally, but when I built an executable I was still having issues. I ended doing as Barmar suggested and require the file be in the home directory. – Jim Rutter Jun 21 '23 at 16:47
  • I don't see how this will solve the problem that it's trying to access the file in the wrong folder. – Barmar Jun 21 '23 at 17:53