How to know the path of the running script in Python?

后端 未结 3 1398
温柔的废话
温柔的废话 2020-12-11 08:26

My script.py creates a temporary file in the same dir as the script.

When running it:

python script.py

it works just file

b

3条回答
  •  鱼传尺愫
    2020-12-11 09:05

    The two current answers reflect the ambiguity of your question.

    When you've run python /path/to/script.py, where do you want your tempfile? In the current directory (./tempfile.txt) or in /path/to/tempfile.txt?

    If the former, you can simply use the relative path (or, for weird and arcane purposes, get the absolute path equivalent to the current directory as @Desintegr suggests, with os.getcwd).

    If the latter, you can learn exactly how the script was invoked with sys.argv[0], as @Jonathan suggests, and manipulate that path with the functions in os.path (of course you can also apply those functions to what os.getcwd returns, if the former case applies), or work with os.path.dirname(__file__) and the like (the latter's necessary if you want this latter behavior also when the script is imported as a module, not just when it's run as a main script).

提交回复
热议问题