gpt4 book ai didi

python - 如何检测自己的文件名

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:30 26 4
gpt4 key购买 nike

我有一些代码,我宁愿不分享,但这是一部分

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 ("...")

没有,程序没有完成,忽略最后一行

最佳答案

也许我误解了你想要什么,但我认为 os.path.basename(__file__) 可以解决问题。

这只会给你路径的文件部分,所以如果你有一个文件foo/bar/baz.py 并像 os.path.basename(' foo/bar/baz.py'),它将返回字符串'baz.py'

所以尝试:

file_name = os.path.basename(__file__)

话虽如此,正如@Blender 指出的那样,您的方法似乎有点不典型,而且我从未尝试过以这种方式让程序自行重启。我不确定这个答案是否能让你的程序正常工作,但它会给你运行你的程序的文件的名称,这似乎是你正在寻找的。

关于python - 如何检测自己的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com