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

标签 python

我有一些代码,我不想分享,但这只是一部分

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/

相关文章:

python - 使用 Subprocess (Python) 发送 CMD 命令提示符

python - Pandas GroupBy.apply 方法复制第一组

python - cv2.convexityDefects 错误

python - MySQL 中的休眠进程

Python 记录器,打印没有父名称的子记录器 %(name)

python - 如何将字符串 append 到 float 列表

python 3 : Don't show full directory path on error message

python - 如何打印 python 数组中的列?

python - 如何检查 *args[0] 是否存在?

python - 无法在 Django Rest 框架中上传图像并获得预期行为