How do I get the path of the current executed file in Python?

前端 未结 13 2339
天命终不由人
天命终不由人 2020-11-22 17:06

This may seem like a newbie question, but it is not. Some common approaches don\'t work in all cases:

sys.argv[0]

This means using path = os.path.abs

相关标签:
13条回答
  • 2020-11-22 17:21

    My solution is:

    import os
    print(os.path.dirname(os.path.abspath(__file__)))
    
    0 讨论(0)
  • 2020-11-22 17:22

    Simply add the following:

    from sys import *
    path_to_current_file = sys.argv[0]
    print(path_to_current_file)
    

    Or:

    from sys import *
    print(sys.argv[0])
    
    0 讨论(0)
  • 2020-11-22 17:23
    import os
    current_file_path=os.path.dirname(os.path.realpath('__file__'))
    
    0 讨论(0)
  • 2020-11-22 17:24

    First, you need to import from inspect and os

    from inspect import getsourcefile
    from os.path import abspath
    

    Next, wherever you want to find the source file from you just use

    abspath(getsourcefile(lambda:0))
    
    0 讨论(0)
  • 2020-11-22 17:32

    See my answer to the question Importing modules from parent folder for related information, including why my answer doesn't use the unreliable __file__ variable. This simple solution should be cross-compatible with different operating systems as the modules os and inspect come as part of Python.

    First, you need to import parts of the inspect and os modules.

    from inspect import getsourcefile
    from os.path import abspath
    

    Next, use the following line anywhere else it's needed in your Python code:

    abspath(getsourcefile(lambda:0))
    

    How it works:

    From the built-in module os (description below), the abspath tool is imported.

    OS routines for Mac, NT, or Posix depending on what system we're on.

    Then getsourcefile (description below) is imported from the built-in module inspect.

    Get useful information from live Python objects.

    • abspath(path) returns the absolute/full version of a file path
    • getsourcefile(lambda:0) somehow gets the internal source file of the lambda function object, so returns '<pyshell#nn>' in the Python shell or returns the file path of the Python code currently being executed.

    Using abspath on the result of getsourcefile(lambda:0) should make sure that the file path generated is the full file path of the Python file.
    This explained solution was originally based on code from the answer at How do I get the path of the current executed file in Python?.

    0 讨论(0)
  • 2020-11-22 17:33

    this solution is robust even in executables

    import inspect, os.path
    
    filename = inspect.getframeinfo(inspect.currentframe()).filename
    path     = os.path.dirname(os.path.abspath(filename))
    
    0 讨论(0)
提交回复
热议问题