我有一些代码,我宁愿不分享,但这部分
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()
我希望文件自己打开(从头开始)我已经测试了它并且它可以正常工作但是,如果用户重命名文件(不太可能但可能),那么除非他们反编译,编辑和重新编译,否则它不会工作。所以我想得到它自己的名字,将它存储在一个变量中并像这样打开:
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()
那我怎么得到文件名呢?
编辑:这是我的全部代码:
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 ("...")
不,程序没有完成,忽略了最后一行
答案 0 :(得分:2)
也许我误解了你想要的东西,但我认为os.path.basename(__file__)
会解决问题。
这将只提供路径的文件部分,因此如果您有一个文件foo/bar/baz.py
并传递os.path.basename('foo/bar/baz.py')
之类的路径,它将返回字符串'baz.py'
。
所以试试:
file_name = os.path.basename(__file__)
话虽这么说,你的方法看起来有点不典型,正如@Blender指出的那样,我从来没有试过让程序以这种方式重启。我不确定这个答案是否会使您的程序正常工作,但它会为您提供运行程序的文件的名称,这似乎是您正在寻找的。