如何从Python[3.3]中找到运行Python脚本的目录? 我已经尝试了在:How can I find script's directory with Python?中建议的方法,但是我得到了“无效语法”并指向“os”(我确实导入了os)。
我得到的最接近答案是:sys.argv[0],但它仍然包含文件名,所以我不能使用它。还有别的办法吗?
注: 我对Python还比较陌生。
下面是我到目前为止编写的一些代码(其中rundir=sys.argv[0]是建议的代码所在的部分):
import pygame
from pygame.locals import *
import os, sys
import time
pygame.init()
import statuscheck
print("Completed program status check.")
import mods.modlist
print("Loaded all mods..")
print("Completed loading")
sys.dont_write_bytecode = True
rundir = sys.argv[0]
print("Running from" + rundir)
试试这个:
__file__
获取您所在文件的名称。函数dirname
获取文件所在的目录。语法错误可能与print语句有关。在python 3.x中
无效。打印现在是一项功能。
有效。你需要括号。
要获取包含正在运行的模块的目录:
或者,如果希望调用脚本的目录:
从docs:
根据脚本的调用方式,这可能是来自
os.getcwd()
的相对路径,因此os.path.realpath(__file__)
会将其转换为绝对路径(或者什么也不做,因为__file__
已经是绝对路径)。os.path.dirname()
然后通过删除文件名返回完整目录。这应该有效:
相关问题 更多 >
编程相关推荐