0

How can my Python script reliably get its own location so it can write a file next to itself?

I made a Python script that writes a new file with some working statistics:

import os
NAME = __file__.split('/')[-1]
PATH = os.path.dirname(os.path.realpath(__file__))
PROPER_PATH = os.path.join(MY_PATH, MY_NAME)

with open(os.path.join(PATH, STATS_NAME), 'wb') as statsfile:
    statsfile.write(mystats)

This works great and I can call it from anywhere and it writes the stats file in the same place, next to the script. Apart from when I call the script from a macro VBA script.

The script gets called okay but writes its data to:
    "C:\Users\lsp\AppData\Roaming\Microsoft\Templates"

How do I make sure it writes to the correct path (same as the script path)?

As a work-around I can imagine giving the path as an argument and then providing it in the VBA but surely there's a Pythonic way to achieve the behavior?

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
lsp
  • 51
  • 1
  • 4
  • 1
    There are several related questions already asked and answered. (Note that several times, the "accepted" answer isn't nearly as good as one well below it.) Contenders: "[How to properly determine current script directory in Python?](https://stackoverflow.com/questions/3718657/)"; "[How can I find script's directory with Python?](https://stackoverflow.com/questions/4934806/)"; "[How do I get the path and name of the file that is currently executing?](https://stackoverflow.com/questions/50499/)". – Kevin J. Chase Mar 13 '17 at 02:05
  • [RED MONKEY's answer](https://stackoverflow.com/questions/5475224/4116239) to "[How can I find script's directory with Python?](https://stackoverflow.com/questions/4934806/)" looks like it might solve your problem, since it returns "the directory containing the script that was used to invoke the Python interpreter". Although for logging or storing data, you might be better off with either a hard-coded or user-supplied absolute directory path. – Kevin J. Chase Mar 13 '17 at 02:08

0 Answers0