How to detect own files name
<p>I have some code, which I will rather not share but this a portion</p>

<pre><code>try_again = input ("Try again?")
if answer == "Y" or answer == "y":
     clear()
     file_path = os.path.dirname(os.path.realpath(__file__))
     open file_path + "maze_game.exe"
    exit()
    else:
        exit()
</code></pre>

<p>I want the file to open itself (to start at the beginning) I have tested it and it DOES work but, if the user renames the file (unlikely but possable) clearly this wont work unless they decompile, edit, and recompile. so I want to get the name of itself, store that in a variabe and open like this:</p>

<pre><code>file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
     clear()
     file_path = os.path.dirname(os.path.realpath(__file__))
     open file_path + file_name
    exit()
    else:
        exit()
</code></pre>

<p>so how might I get the file name?</p>

<p>EDIT: here is my whole code:</p>

<pre><code>import os
import time
clear = lambda: os.system('cls')
name = input ("What is your name? ")
friend = "Charels"
if name == "Charels" or name == "charels" or name == "Charles" or name     ==  "charles":
friend = "Chuck"
print ("Welcome to the Maze Game Dr. " + name)
time.sleep(1.5)
clear()
print ("No one has made it out of Colwoods' labrynth,\nhowever there are rumours of untold riches at the end. \nThe most recent victim of the Maze is your best friend, " + friend)
time.sleep(1.5)
clear()
print ("Are you sure you want to continue?")
answer = input ("Y or N? ")
if answer == "Y" or answer == "y":
    ("")
else:
    friend = friend + " for dead. R.I.P."
    print ("Shame on you, you left " + friend)
    time.sleep(1.5)
    clear()
    print ("YOU LOSE")
    time.sleep(1.5)
    clear()
    file_name = how ever I get the name
    try_again = input ("Try again?")
    if answer == "Y" or answer == "y":
         clear()
         file_path = os.path.dirname(os.path.realpath(__file__))
         open file_path + file_name
        exit()
        else:
            exit()
input ("...")
</code></pre>

<p>no, the program is not completed and ignore the last line</p>

<p>Maybe I am misunderstanding what you want, but I think <code>os.path.basename(__file__)</code> will do the trick. </p>

<p>This will give you just the file part of your path, so if you have a file<code>foo/bar/baz.py</code> and pass that path like <code>os.path.basename('foo/bar/baz.py')</code>, it will return the string <code>'baz.py'</code>.</p>

<p>So try:</p>

<pre><code>file_name = os.path.basename(__file__)
</code></pre>

<p>That being said, your approach seems a little atypical as @Blender points out, and I have never tried to have a program restart itself in this way. I am not sure if this answer will make your program work correctly, but it will give you the name of the file that is running your program, which seems to be what you are looking for. </p>

python