Categories
directory python

Find the current directory and file’s directory [duplicate]

2774

How do I determine:

  1. the current directory (where I was in the terminal when I ran the Python script), and
  2. where the Python file I am executing is?

0

    4350

    To get the full path to the directory a Python file is contained in, write this in that file:

    import os 
    dir_path = os.path.dirname(os.path.realpath(__file__))
    

    (Note that the incantation above won’t work if you’ve already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)


    To get the current working directory use

    import os
    cwd = os.getcwd()
    

    Documentation references for the modules, constants and functions used above:

    12

    • 179

      I hate it when I use this to append to sys.path. I feel so dirty right now.

      – FlipMcF

      Sep 26, 2013 at 21:52


    • 12

      file will not work if invoked from an IDE (say IDLE). Suggest os.path.realpath(‘./’) or os.getcwd(). Best anser in here: stackoverflow.com/questions/2632199/…

      – Neon22

      Dec 20, 2013 at 11:12


    • 3

      @Neon22 might suit some needs, but I feel it should be noted that those things aren’t the same at all – files can be outside the working directory.

      – Mark

      Sep 15, 2014 at 17:31

    • 2

      @Moberg Often the paths will be the same when reversing realpath with dirname, but it will differ when the file (or its directory) is actually a symbolic link.

      Mar 17, 2015 at 17:00

    • 5

      It gets an error NameError: name '__file__' is not defined. How to solve this?

      Sep 26, 2016 at 13:15

    362

    Current working directory: os.getcwd()

    And the __file__ attribute can help you find out where the file you are executing is located. This Stack Overflow post explains everything: How do I get the path of the current executed file in Python?

      337

      You may find this useful as a reference:

      import os
      
      print("Path at terminal when executing this file")
      print(os.getcwd() + "\n")
      
      print("This file path, relative to os.getcwd()")
      print(__file__ + "\n")
      
      print("This file full path (following symlinks)")
      full_path = os.path.realpath(__file__)
      print(full_path + "\n")
      
      print("This file directory and name")
      path, filename = os.path.split(full_path)
      print(path + ' --> ' + filename + "\n")
      
      print("This file directory only")
      print(os.path.dirname(full_path))
      

      2

      • 12

        what does __file__ signifies here? It does not work for me.

        Jun 17, 2016 at 15:22


      • 13

        The __file__ is an attribute of the module object. You need run the code inside a Python file, not on the REPL.

        Jun 20, 2016 at 13:07