How to find the directory of the .app that a python script is running from
<p>I recently made a python script that goes through files in whatever directory it is placed in and renames them based on certain criteria. The script works perfectly, and I compiled the script into an OS X .app using py2app. This worked fine as well. However now when I run the script, it searches through the files in the ".app/contents/macOS" folder (where the script is located) rather than where the ".app" is actually located.</p>

<p>This is because it has this code at the start:</p>

<pre><code>src = os.path.dirname(os.path.abspath(__file__))
</code></pre>

<p>which assigns the the location of the ".py" file to a variable which is then used extensively throughout the script. Is there any way I can instead add a snippet of code which tells python the path location of the ".app" that the ".py" file is executing from?</p>

<p>If not, perhaps there is a way to get a file explorer window open, from there it would be possible for a user to select a folder who's path would then get assigned to the "src" variable. I'm very new to python however so this would certainly be a challenge.</p>

<p>To find the location of the <code>.app</code> directory that wraps the application, the most direct way is to modify the path that you find with your current code. After computing <code>src</code> as you did, just trim it like this and use <code>app</code> as the path:</p>

<pre><code>import re
...
app, rest = re.split(r"/[^/]*\.app/", src, 1)
</code></pre>

<p>This stops at the first path component that ends in <code>.app</code>. If you prefer you can hard-code your application name, e.g. <code>/myprogram.app/</code>.</p>

<p>PS. I'm puzzled as to why you copy your app to the folder you want to modify. A file selection dialog, or drag and drop, is the more common (and easier) way to tell a program what to work on. OS X applications created with <code>py2app</code> support drag and drop: Your program can get the path to the dropped directory like this:</p>

<pre><code>import sys
folders = sys.argv[1:]   # Handles multiple arguments
for folder in folders:
    do_something_in(folder)
</code></pre>

<p>Then simply drag and drop the directory or directories you want to process onto the application icon, which you can just keep on your desktop, the Finder's sidebar, or a favorite directory -- no need to copy it each time you use it, and no need for it to know where its source is.</p>

python osx python-3.x py2app