How to get full path of current file's directory in Python?












555















I want to get the current file's directory path.

I tried:



>>> os.path.abspath(__file__)
'C:\python27\test.py'


But how can I retrieve the directory's path?
For example:



'C:\python27\'









share|improve this question




















  • 3





    possible duplicate of Find current directory and file's directory

    – user2284570
    May 23 '14 at 15:01






  • 4





    __file__ is not defined when you run python as an interactive shell. The first piece of code in your question looks like it's from an interactive shell, but would actually produce a NameError, at least on python 2.7.3, but others too I guess.

    – drevicko
    May 31 '15 at 1:04


















555















I want to get the current file's directory path.

I tried:



>>> os.path.abspath(__file__)
'C:\python27\test.py'


But how can I retrieve the directory's path?
For example:



'C:\python27\'









share|improve this question




















  • 3





    possible duplicate of Find current directory and file's directory

    – user2284570
    May 23 '14 at 15:01






  • 4





    __file__ is not defined when you run python as an interactive shell. The first piece of code in your question looks like it's from an interactive shell, but would actually produce a NameError, at least on python 2.7.3, but others too I guess.

    – drevicko
    May 31 '15 at 1:04
















555












555








555


115






I want to get the current file's directory path.

I tried:



>>> os.path.abspath(__file__)
'C:\python27\test.py'


But how can I retrieve the directory's path?
For example:



'C:\python27\'









share|improve this question
















I want to get the current file's directory path.

I tried:



>>> os.path.abspath(__file__)
'C:\python27\test.py'


But how can I retrieve the directory's path?
For example:



'C:\python27\'






python filesystems






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 18 '14 at 21:58









Ciro Santilli 新疆改造中心 六四事件 法轮功

147k34558473




147k34558473










asked Aug 7 '10 at 12:17









ShubhamShubham

6,313154678




6,313154678








  • 3





    possible duplicate of Find current directory and file's directory

    – user2284570
    May 23 '14 at 15:01






  • 4





    __file__ is not defined when you run python as an interactive shell. The first piece of code in your question looks like it's from an interactive shell, but would actually produce a NameError, at least on python 2.7.3, but others too I guess.

    – drevicko
    May 31 '15 at 1:04
















  • 3





    possible duplicate of Find current directory and file's directory

    – user2284570
    May 23 '14 at 15:01






  • 4





    __file__ is not defined when you run python as an interactive shell. The first piece of code in your question looks like it's from an interactive shell, but would actually produce a NameError, at least on python 2.7.3, but others too I guess.

    – drevicko
    May 31 '15 at 1:04










3




3





possible duplicate of Find current directory and file's directory

– user2284570
May 23 '14 at 15:01





possible duplicate of Find current directory and file's directory

– user2284570
May 23 '14 at 15:01




4




4





__file__ is not defined when you run python as an interactive shell. The first piece of code in your question looks like it's from an interactive shell, but would actually produce a NameError, at least on python 2.7.3, but others too I guess.

– drevicko
May 31 '15 at 1:04







__file__ is not defined when you run python as an interactive shell. The first piece of code in your question looks like it's from an interactive shell, but would actually produce a NameError, at least on python 2.7.3, but others too I guess.

– drevicko
May 31 '15 at 1:04














11 Answers
11






active

oldest

votes


















1163














If you mean the directory of the script being run:



import os
os.path.dirname(os.path.abspath(__file__))


If you mean the current working directory:



import os
os.getcwd()


Note that before and after file is two underscores, not just one.



Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.






share|improve this answer





















  • 34





    abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

    – sorin
    Oct 25 '11 at 10:10






  • 4





    should be os.path.dirname(os.path.abspath(os.__file__))?

    – DrBailey
    Mar 27 '14 at 12:28






  • 2





    @DrBailey: no, there's nothing special about ActivePython. __file__ (note that it's two underscores on either side of the word) is a standard part of python. It's not available in C-based modules, for example, but it should always be available in a python script.

    – Bryan Oakley
    Apr 17 '14 at 21:32






  • 7





    I would recommend using realpath instead of abspath to resolve a possible symbolic link.

    – TTimo
    Jan 9 '15 at 21:37






  • 7





    @cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt.

    – Bryan Oakley
    Aug 11 '16 at 21:57



















34














In Python 3:



from pathlib import Path

mypath = Path().absolute()
print(mypath)





share|improve this answer





















  • 7





    I had to do Path(__file__).parent to get the folder that is containing the file

    – YellowPillow
    Jun 6 '18 at 4:09













  • That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

    – Ron Kalian
    Jun 6 '18 at 8:18











  • Sorry I should've have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you're calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

    – YellowPillow
    Jun 6 '18 at 12:22











  • @YellowPillow Path(__file__).cwd() is more explicit

    – Charles
    Feb 8 at 16:00











  • Path(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.

    – Ron Kalian
    Feb 8 at 16:09



















9














import os
print os.path.dirname(__file__)





share|improve this answer



















  • 19





    Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

    – sorin
    Oct 25 '11 at 10:11






  • 1





    It will give / as output

    – Tripathi29
    Sep 24 '15 at 6:31








  • 1





    @sorin Actually on Python 3.6 they are both the same

    – Akshay L Aradhya
    Apr 2 '18 at 12:25



















5














You can use os and os.path library easily as follows



import os
os.chdir(os.path.dirname(os.getcwd()))


os.path.dirname returns upper directory from current one.
It lets us change to an upper level without passing any file argument and without knowing absolute path.






share|improve this answer





















  • 6





    This does not give the directory of the current file. It returns the directory of the current working directory which could be completely different. What you suggest only works if the file is in the current working directory.

    – Bryan Oakley
    Jul 1 '16 at 19:34



















1














In Python 3.x I do:



from pathlib import Path

path = Path(__file__).parent.absolute()


Explanation:





  • Path(__file__) is the path to the current file.


  • .parent gives you the directory the file is in.


  • .absolute() gives you the full absolute path to it.


Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).






share|improve this answer































    0














    IPython has a magic command %pwd to get the present working directory. It can be used in following way:



    from IPython.terminal.embed import InteractiveShellEmbed

    ip_shell = InteractiveShellEmbed()

    present_working_directory = ip_shell.magic("%pwd")


    On IPython Jupyter Notebook %pwd can be used directly as following:



    present_working_directory = %pwd





    share|improve this answer



















    • 2





      The question isn't about IPython

      – Kiro
      Apr 10 '18 at 8:07








    • 1





      @Kiro, my solution answers the question using IPython. For example If some one answers a question with a solution using a new library then also imho it remains a pertinent answer to the question.

      – Nafeez Quraishi
      Apr 11 '18 at 9:36





















    0














    To keep the migration consistency across platforms (macOS/Windows/Linux), try:



    path = r'%s' % os.getcwd().replace('\','/')





    share|improve this answer

































      0














      I have made a function to use when running python under IIS in CGI in order to get the current folder:



      import os 
      def getLocalFolder():
      path=str(os.path.dirname(os.path.abspath(__file__))).split('\')
      return path[len(path)-1]





      share|improve this answer































        0














        System: MacOS



        Version: Python 3.6 w/ Anaconda



        import os
        rootpath = os.getcwd()
        os.chdir(rootpath)






        share|improve this answer































          0














          USEFUL PATH PROPERTIES IN PYTHON:



           from pathlib import Path

          #Returns the path of the directory, where your script file is placed
          mypath = Path().absolute()
          print('Absolute path : {}'.format(mypath))

          #if you want to go to any other file inside the subdirectories of the directory path got from above method
          filePath = mypath/'data'/'fuel_econ.csv'
          print('File path : {}'.format(filePath))

          #To check if file present in that directory or Not
          isfileExist = filePath.exists()
          print('isfileExist : {}'.format(isfileExist))

          #To check if the path is a directory or a File
          isadirectory = filePath.is_dir()
          print('isadirectory : {}'.format(isadirectory))

          #To get the extension of the file
          fileExtension = mypath/'data'/'fuel_econ.csv'
          print('File extension : {}'.format(filePath.suffix))


          OUTPUT:
          ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED



          Absolute path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2



          File path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2datafuel_econ.csv



          isfileExist : True



          isadirectory : False



          File extension : .csv






          share|improve this answer

































            -1














            ## IMPORT MODULES
            import os

            ## CALCULATE FILEPATH VARIABLE
            filepath = os.path.abspath('') ## ~ os.getcwd()
            ## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
            ## ..OR DIFFERENT IN SOME CIRCUMSTANCES





            share|improve this answer





















            • 2





              The current working directory might not be the same as the directory of the current file. Your solution will only work if the current working directory is the same as the directory that holds the file. That can be fairly common during development, but is usually pretty rare for a deployed script.

              – Bryan Oakley
              Jan 3 at 22:45











            • Thanks for the info. I updated my answer to reflect the possibility that these may not be equivalent returning the same filepath. Such is reason why I adhere to philosophy of coding called "incremental programming", testing, and lots of print() function calls to test output and/or values return at each step of the way. I hope my code now better reflects the reality of os.path.abspath() vs. os.getcwd() since I do not claim to know everything. However you can see that I put os.getcwd() in comments as not the main solution, but rather as an alt piece of code worth remembering and checking.

              – Jerusalem Programmer
              Jan 6 at 8:45











            • P.S. I think someone edited and erased the majority of my answer that I posted here... :( Such discourages people from participating if their answers are going to be censored and chopped.

              – Jerusalem Programmer
              Jan 6 at 8:49











            • You're the only person to have edited this answer. Also, your edits still don't properly answer the question. The question is specifically asking about the path to the file's directory, and your answer only mentions getting the current directory. That is not a correct answer, since the current directory is very often not the same as the directory the script is in. This has nothing to do with abspath.

              – Bryan Oakley
              Jan 6 at 14:49













            • Most certainly the code I shared gives path to the file's directory if run from the directory and/or file from where you want to know the absolute file path. Most certainly it is a correct answer. Please don't be a troll.

              – Jerusalem Programmer
              Jan 7 at 4:48











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3430372%2fhow-to-get-full-path-of-current-files-directory-in-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            11 Answers
            11






            active

            oldest

            votes








            11 Answers
            11






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1163














            If you mean the directory of the script being run:



            import os
            os.path.dirname(os.path.abspath(__file__))


            If you mean the current working directory:



            import os
            os.getcwd()


            Note that before and after file is two underscores, not just one.



            Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.






            share|improve this answer





















            • 34





              abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

              – sorin
              Oct 25 '11 at 10:10






            • 4





              should be os.path.dirname(os.path.abspath(os.__file__))?

              – DrBailey
              Mar 27 '14 at 12:28






            • 2





              @DrBailey: no, there's nothing special about ActivePython. __file__ (note that it's two underscores on either side of the word) is a standard part of python. It's not available in C-based modules, for example, but it should always be available in a python script.

              – Bryan Oakley
              Apr 17 '14 at 21:32






            • 7





              I would recommend using realpath instead of abspath to resolve a possible symbolic link.

              – TTimo
              Jan 9 '15 at 21:37






            • 7





              @cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt.

              – Bryan Oakley
              Aug 11 '16 at 21:57
















            1163














            If you mean the directory of the script being run:



            import os
            os.path.dirname(os.path.abspath(__file__))


            If you mean the current working directory:



            import os
            os.getcwd()


            Note that before and after file is two underscores, not just one.



            Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.






            share|improve this answer





















            • 34





              abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

              – sorin
              Oct 25 '11 at 10:10






            • 4





              should be os.path.dirname(os.path.abspath(os.__file__))?

              – DrBailey
              Mar 27 '14 at 12:28






            • 2





              @DrBailey: no, there's nothing special about ActivePython. __file__ (note that it's two underscores on either side of the word) is a standard part of python. It's not available in C-based modules, for example, but it should always be available in a python script.

              – Bryan Oakley
              Apr 17 '14 at 21:32






            • 7





              I would recommend using realpath instead of abspath to resolve a possible symbolic link.

              – TTimo
              Jan 9 '15 at 21:37






            • 7





              @cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt.

              – Bryan Oakley
              Aug 11 '16 at 21:57














            1163












            1163








            1163







            If you mean the directory of the script being run:



            import os
            os.path.dirname(os.path.abspath(__file__))


            If you mean the current working directory:



            import os
            os.getcwd()


            Note that before and after file is two underscores, not just one.



            Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.






            share|improve this answer















            If you mean the directory of the script being run:



            import os
            os.path.dirname(os.path.abspath(__file__))


            If you mean the current working directory:



            import os
            os.getcwd()


            Note that before and after file is two underscores, not just one.



            Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 3 at 22:42

























            answered Aug 7 '10 at 12:24









            Bryan OakleyBryan Oakley

            221k22274434




            221k22274434








            • 34





              abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

              – sorin
              Oct 25 '11 at 10:10






            • 4





              should be os.path.dirname(os.path.abspath(os.__file__))?

              – DrBailey
              Mar 27 '14 at 12:28






            • 2





              @DrBailey: no, there's nothing special about ActivePython. __file__ (note that it's two underscores on either side of the word) is a standard part of python. It's not available in C-based modules, for example, but it should always be available in a python script.

              – Bryan Oakley
              Apr 17 '14 at 21:32






            • 7





              I would recommend using realpath instead of abspath to resolve a possible symbolic link.

              – TTimo
              Jan 9 '15 at 21:37






            • 7





              @cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt.

              – Bryan Oakley
              Aug 11 '16 at 21:57














            • 34





              abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

              – sorin
              Oct 25 '11 at 10:10






            • 4





              should be os.path.dirname(os.path.abspath(os.__file__))?

              – DrBailey
              Mar 27 '14 at 12:28






            • 2





              @DrBailey: no, there's nothing special about ActivePython. __file__ (note that it's two underscores on either side of the word) is a standard part of python. It's not available in C-based modules, for example, but it should always be available in a python script.

              – Bryan Oakley
              Apr 17 '14 at 21:32






            • 7





              I would recommend using realpath instead of abspath to resolve a possible symbolic link.

              – TTimo
              Jan 9 '15 at 21:37






            • 7





              @cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt.

              – Bryan Oakley
              Aug 11 '16 at 21:57








            34




            34





            abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

            – sorin
            Oct 25 '11 at 10:10





            abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

            – sorin
            Oct 25 '11 at 10:10




            4




            4





            should be os.path.dirname(os.path.abspath(os.__file__))?

            – DrBailey
            Mar 27 '14 at 12:28





            should be os.path.dirname(os.path.abspath(os.__file__))?

            – DrBailey
            Mar 27 '14 at 12:28




            2




            2





            @DrBailey: no, there's nothing special about ActivePython. __file__ (note that it's two underscores on either side of the word) is a standard part of python. It's not available in C-based modules, for example, but it should always be available in a python script.

            – Bryan Oakley
            Apr 17 '14 at 21:32





            @DrBailey: no, there's nothing special about ActivePython. __file__ (note that it's two underscores on either side of the word) is a standard part of python. It's not available in C-based modules, for example, but it should always be available in a python script.

            – Bryan Oakley
            Apr 17 '14 at 21:32




            7




            7





            I would recommend using realpath instead of abspath to resolve a possible symbolic link.

            – TTimo
            Jan 9 '15 at 21:37





            I would recommend using realpath instead of abspath to resolve a possible symbolic link.

            – TTimo
            Jan 9 '15 at 21:37




            7




            7





            @cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt.

            – Bryan Oakley
            Aug 11 '16 at 21:57





            @cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt.

            – Bryan Oakley
            Aug 11 '16 at 21:57













            34














            In Python 3:



            from pathlib import Path

            mypath = Path().absolute()
            print(mypath)





            share|improve this answer





















            • 7





              I had to do Path(__file__).parent to get the folder that is containing the file

              – YellowPillow
              Jun 6 '18 at 4:09













            • That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

              – Ron Kalian
              Jun 6 '18 at 8:18











            • Sorry I should've have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you're calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

              – YellowPillow
              Jun 6 '18 at 12:22











            • @YellowPillow Path(__file__).cwd() is more explicit

              – Charles
              Feb 8 at 16:00











            • Path(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.

              – Ron Kalian
              Feb 8 at 16:09
















            34














            In Python 3:



            from pathlib import Path

            mypath = Path().absolute()
            print(mypath)





            share|improve this answer





















            • 7





              I had to do Path(__file__).parent to get the folder that is containing the file

              – YellowPillow
              Jun 6 '18 at 4:09













            • That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

              – Ron Kalian
              Jun 6 '18 at 8:18











            • Sorry I should've have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you're calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

              – YellowPillow
              Jun 6 '18 at 12:22











            • @YellowPillow Path(__file__).cwd() is more explicit

              – Charles
              Feb 8 at 16:00











            • Path(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.

              – Ron Kalian
              Feb 8 at 16:09














            34












            34








            34







            In Python 3:



            from pathlib import Path

            mypath = Path().absolute()
            print(mypath)





            share|improve this answer















            In Python 3:



            from pathlib import Path

            mypath = Path().absolute()
            print(mypath)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 15 '18 at 20:56









            A-B-B

            24.2k66370




            24.2k66370










            answered Apr 30 '18 at 10:51









            Ron KalianRon Kalian

            806515




            806515








            • 7





              I had to do Path(__file__).parent to get the folder that is containing the file

              – YellowPillow
              Jun 6 '18 at 4:09













            • That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

              – Ron Kalian
              Jun 6 '18 at 8:18











            • Sorry I should've have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you're calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

              – YellowPillow
              Jun 6 '18 at 12:22











            • @YellowPillow Path(__file__).cwd() is more explicit

              – Charles
              Feb 8 at 16:00











            • Path(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.

              – Ron Kalian
              Feb 8 at 16:09














            • 7





              I had to do Path(__file__).parent to get the folder that is containing the file

              – YellowPillow
              Jun 6 '18 at 4:09













            • That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

              – Ron Kalian
              Jun 6 '18 at 8:18











            • Sorry I should've have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you're calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

              – YellowPillow
              Jun 6 '18 at 12:22











            • @YellowPillow Path(__file__).cwd() is more explicit

              – Charles
              Feb 8 at 16:00











            • Path(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.

              – Ron Kalian
              Feb 8 at 16:09








            7




            7





            I had to do Path(__file__).parent to get the folder that is containing the file

            – YellowPillow
            Jun 6 '18 at 4:09







            I had to do Path(__file__).parent to get the folder that is containing the file

            – YellowPillow
            Jun 6 '18 at 4:09















            That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

            – Ron Kalian
            Jun 6 '18 at 8:18





            That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

            – Ron Kalian
            Jun 6 '18 at 8:18













            Sorry I should've have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you're calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

            – YellowPillow
            Jun 6 '18 at 12:22





            Sorry I should've have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you're calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

            – YellowPillow
            Jun 6 '18 at 12:22













            @YellowPillow Path(__file__).cwd() is more explicit

            – Charles
            Feb 8 at 16:00





            @YellowPillow Path(__file__).cwd() is more explicit

            – Charles
            Feb 8 at 16:00













            Path(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.

            – Ron Kalian
            Feb 8 at 16:09





            Path(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.

            – Ron Kalian
            Feb 8 at 16:09











            9














            import os
            print os.path.dirname(__file__)





            share|improve this answer



















            • 19





              Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

              – sorin
              Oct 25 '11 at 10:11






            • 1





              It will give / as output

              – Tripathi29
              Sep 24 '15 at 6:31








            • 1





              @sorin Actually on Python 3.6 they are both the same

              – Akshay L Aradhya
              Apr 2 '18 at 12:25
















            9














            import os
            print os.path.dirname(__file__)





            share|improve this answer



















            • 19





              Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

              – sorin
              Oct 25 '11 at 10:11






            • 1





              It will give / as output

              – Tripathi29
              Sep 24 '15 at 6:31








            • 1





              @sorin Actually on Python 3.6 they are both the same

              – Akshay L Aradhya
              Apr 2 '18 at 12:25














            9












            9








            9







            import os
            print os.path.dirname(__file__)





            share|improve this answer













            import os
            print os.path.dirname(__file__)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 7 '10 at 12:24









            chefsmartchefsmart

            3,84283446




            3,84283446








            • 19





              Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

              – sorin
              Oct 25 '11 at 10:11






            • 1





              It will give / as output

              – Tripathi29
              Sep 24 '15 at 6:31








            • 1





              @sorin Actually on Python 3.6 they are both the same

              – Akshay L Aradhya
              Apr 2 '18 at 12:25














            • 19





              Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

              – sorin
              Oct 25 '11 at 10:11






            • 1





              It will give / as output

              – Tripathi29
              Sep 24 '15 at 6:31








            • 1





              @sorin Actually on Python 3.6 they are both the same

              – Akshay L Aradhya
              Apr 2 '18 at 12:25








            19




            19





            Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

            – sorin
            Oct 25 '11 at 10:11





            Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

            – sorin
            Oct 25 '11 at 10:11




            1




            1





            It will give / as output

            – Tripathi29
            Sep 24 '15 at 6:31







            It will give / as output

            – Tripathi29
            Sep 24 '15 at 6:31






            1




            1





            @sorin Actually on Python 3.6 they are both the same

            – Akshay L Aradhya
            Apr 2 '18 at 12:25





            @sorin Actually on Python 3.6 they are both the same

            – Akshay L Aradhya
            Apr 2 '18 at 12:25











            5














            You can use os and os.path library easily as follows



            import os
            os.chdir(os.path.dirname(os.getcwd()))


            os.path.dirname returns upper directory from current one.
            It lets us change to an upper level without passing any file argument and without knowing absolute path.






            share|improve this answer





















            • 6





              This does not give the directory of the current file. It returns the directory of the current working directory which could be completely different. What you suggest only works if the file is in the current working directory.

              – Bryan Oakley
              Jul 1 '16 at 19:34
















            5














            You can use os and os.path library easily as follows



            import os
            os.chdir(os.path.dirname(os.getcwd()))


            os.path.dirname returns upper directory from current one.
            It lets us change to an upper level without passing any file argument and without knowing absolute path.






            share|improve this answer





















            • 6





              This does not give the directory of the current file. It returns the directory of the current working directory which could be completely different. What you suggest only works if the file is in the current working directory.

              – Bryan Oakley
              Jul 1 '16 at 19:34














            5












            5








            5







            You can use os and os.path library easily as follows



            import os
            os.chdir(os.path.dirname(os.getcwd()))


            os.path.dirname returns upper directory from current one.
            It lets us change to an upper level without passing any file argument and without knowing absolute path.






            share|improve this answer















            You can use os and os.path library easily as follows



            import os
            os.chdir(os.path.dirname(os.getcwd()))


            os.path.dirname returns upper directory from current one.
            It lets us change to an upper level without passing any file argument and without knowing absolute path.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 2 '17 at 18:38









            Paolo

            10.3k1467103




            10.3k1467103










            answered Oct 16 '14 at 13:05









            mulg0rmulg0r

            1,51311222




            1,51311222








            • 6





              This does not give the directory of the current file. It returns the directory of the current working directory which could be completely different. What you suggest only works if the file is in the current working directory.

              – Bryan Oakley
              Jul 1 '16 at 19:34














            • 6





              This does not give the directory of the current file. It returns the directory of the current working directory which could be completely different. What you suggest only works if the file is in the current working directory.

              – Bryan Oakley
              Jul 1 '16 at 19:34








            6




            6





            This does not give the directory of the current file. It returns the directory of the current working directory which could be completely different. What you suggest only works if the file is in the current working directory.

            – Bryan Oakley
            Jul 1 '16 at 19:34





            This does not give the directory of the current file. It returns the directory of the current working directory which could be completely different. What you suggest only works if the file is in the current working directory.

            – Bryan Oakley
            Jul 1 '16 at 19:34











            1














            In Python 3.x I do:



            from pathlib import Path

            path = Path(__file__).parent.absolute()


            Explanation:





            • Path(__file__) is the path to the current file.


            • .parent gives you the directory the file is in.


            • .absolute() gives you the full absolute path to it.


            Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).






            share|improve this answer




























              1














              In Python 3.x I do:



              from pathlib import Path

              path = Path(__file__).parent.absolute()


              Explanation:





              • Path(__file__) is the path to the current file.


              • .parent gives you the directory the file is in.


              • .absolute() gives you the full absolute path to it.


              Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).






              share|improve this answer


























                1












                1








                1







                In Python 3.x I do:



                from pathlib import Path

                path = Path(__file__).parent.absolute()


                Explanation:





                • Path(__file__) is the path to the current file.


                • .parent gives you the directory the file is in.


                • .absolute() gives you the full absolute path to it.


                Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).






                share|improve this answer













                In Python 3.x I do:



                from pathlib import Path

                path = Path(__file__).parent.absolute()


                Explanation:





                • Path(__file__) is the path to the current file.


                • .parent gives you the directory the file is in.


                • .absolute() gives you the full absolute path to it.


                Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 26 at 18:36









                ArminiusArminius

                452514




                452514























                    0














                    IPython has a magic command %pwd to get the present working directory. It can be used in following way:



                    from IPython.terminal.embed import InteractiveShellEmbed

                    ip_shell = InteractiveShellEmbed()

                    present_working_directory = ip_shell.magic("%pwd")


                    On IPython Jupyter Notebook %pwd can be used directly as following:



                    present_working_directory = %pwd





                    share|improve this answer



















                    • 2





                      The question isn't about IPython

                      – Kiro
                      Apr 10 '18 at 8:07








                    • 1





                      @Kiro, my solution answers the question using IPython. For example If some one answers a question with a solution using a new library then also imho it remains a pertinent answer to the question.

                      – Nafeez Quraishi
                      Apr 11 '18 at 9:36


















                    0














                    IPython has a magic command %pwd to get the present working directory. It can be used in following way:



                    from IPython.terminal.embed import InteractiveShellEmbed

                    ip_shell = InteractiveShellEmbed()

                    present_working_directory = ip_shell.magic("%pwd")


                    On IPython Jupyter Notebook %pwd can be used directly as following:



                    present_working_directory = %pwd





                    share|improve this answer



















                    • 2





                      The question isn't about IPython

                      – Kiro
                      Apr 10 '18 at 8:07








                    • 1





                      @Kiro, my solution answers the question using IPython. For example If some one answers a question with a solution using a new library then also imho it remains a pertinent answer to the question.

                      – Nafeez Quraishi
                      Apr 11 '18 at 9:36
















                    0












                    0








                    0







                    IPython has a magic command %pwd to get the present working directory. It can be used in following way:



                    from IPython.terminal.embed import InteractiveShellEmbed

                    ip_shell = InteractiveShellEmbed()

                    present_working_directory = ip_shell.magic("%pwd")


                    On IPython Jupyter Notebook %pwd can be used directly as following:



                    present_working_directory = %pwd





                    share|improve this answer













                    IPython has a magic command %pwd to get the present working directory. It can be used in following way:



                    from IPython.terminal.embed import InteractiveShellEmbed

                    ip_shell = InteractiveShellEmbed()

                    present_working_directory = ip_shell.magic("%pwd")


                    On IPython Jupyter Notebook %pwd can be used directly as following:



                    present_working_directory = %pwd






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 7 '18 at 5:50









                    Nafeez QuraishiNafeez Quraishi

                    595717




                    595717








                    • 2





                      The question isn't about IPython

                      – Kiro
                      Apr 10 '18 at 8:07








                    • 1





                      @Kiro, my solution answers the question using IPython. For example If some one answers a question with a solution using a new library then also imho it remains a pertinent answer to the question.

                      – Nafeez Quraishi
                      Apr 11 '18 at 9:36
















                    • 2





                      The question isn't about IPython

                      – Kiro
                      Apr 10 '18 at 8:07








                    • 1





                      @Kiro, my solution answers the question using IPython. For example If some one answers a question with a solution using a new library then also imho it remains a pertinent answer to the question.

                      – Nafeez Quraishi
                      Apr 11 '18 at 9:36










                    2




                    2





                    The question isn't about IPython

                    – Kiro
                    Apr 10 '18 at 8:07







                    The question isn't about IPython

                    – Kiro
                    Apr 10 '18 at 8:07






                    1




                    1





                    @Kiro, my solution answers the question using IPython. For example If some one answers a question with a solution using a new library then also imho it remains a pertinent answer to the question.

                    – Nafeez Quraishi
                    Apr 11 '18 at 9:36







                    @Kiro, my solution answers the question using IPython. For example If some one answers a question with a solution using a new library then also imho it remains a pertinent answer to the question.

                    – Nafeez Quraishi
                    Apr 11 '18 at 9:36













                    0














                    To keep the migration consistency across platforms (macOS/Windows/Linux), try:



                    path = r'%s' % os.getcwd().replace('\','/')





                    share|improve this answer






























                      0














                      To keep the migration consistency across platforms (macOS/Windows/Linux), try:



                      path = r'%s' % os.getcwd().replace('\','/')





                      share|improve this answer




























                        0












                        0








                        0







                        To keep the migration consistency across platforms (macOS/Windows/Linux), try:



                        path = r'%s' % os.getcwd().replace('\','/')





                        share|improve this answer















                        To keep the migration consistency across platforms (macOS/Windows/Linux), try:



                        path = r'%s' % os.getcwd().replace('\','/')






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Apr 12 '18 at 7:33

























                        answered Apr 12 '18 at 5:16









                        Qiao ZhangQiao Zhang

                        11716




                        11716























                            0














                            I have made a function to use when running python under IIS in CGI in order to get the current folder:



                            import os 
                            def getLocalFolder():
                            path=str(os.path.dirname(os.path.abspath(__file__))).split('\')
                            return path[len(path)-1]





                            share|improve this answer




























                              0














                              I have made a function to use when running python under IIS in CGI in order to get the current folder:



                              import os 
                              def getLocalFolder():
                              path=str(os.path.dirname(os.path.abspath(__file__))).split('\')
                              return path[len(path)-1]





                              share|improve this answer


























                                0












                                0








                                0







                                I have made a function to use when running python under IIS in CGI in order to get the current folder:



                                import os 
                                def getLocalFolder():
                                path=str(os.path.dirname(os.path.abspath(__file__))).split('\')
                                return path[len(path)-1]





                                share|improve this answer













                                I have made a function to use when running python under IIS in CGI in order to get the current folder:



                                import os 
                                def getLocalFolder():
                                path=str(os.path.dirname(os.path.abspath(__file__))).split('\')
                                return path[len(path)-1]






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Dec 27 '18 at 10:35









                                Gil AllenGil Allen

                                882920




                                882920























                                    0














                                    System: MacOS



                                    Version: Python 3.6 w/ Anaconda



                                    import os
                                    rootpath = os.getcwd()
                                    os.chdir(rootpath)






                                    share|improve this answer




























                                      0














                                      System: MacOS



                                      Version: Python 3.6 w/ Anaconda



                                      import os
                                      rootpath = os.getcwd()
                                      os.chdir(rootpath)






                                      share|improve this answer


























                                        0












                                        0








                                        0







                                        System: MacOS



                                        Version: Python 3.6 w/ Anaconda



                                        import os
                                        rootpath = os.getcwd()
                                        os.chdir(rootpath)






                                        share|improve this answer













                                        System: MacOS



                                        Version: Python 3.6 w/ Anaconda



                                        import os
                                        rootpath = os.getcwd()
                                        os.chdir(rootpath)







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jan 30 at 1:42









                                        Suyang XuSuyang Xu

                                        112




                                        112























                                            0














                                            USEFUL PATH PROPERTIES IN PYTHON:



                                             from pathlib import Path

                                            #Returns the path of the directory, where your script file is placed
                                            mypath = Path().absolute()
                                            print('Absolute path : {}'.format(mypath))

                                            #if you want to go to any other file inside the subdirectories of the directory path got from above method
                                            filePath = mypath/'data'/'fuel_econ.csv'
                                            print('File path : {}'.format(filePath))

                                            #To check if file present in that directory or Not
                                            isfileExist = filePath.exists()
                                            print('isfileExist : {}'.format(isfileExist))

                                            #To check if the path is a directory or a File
                                            isadirectory = filePath.is_dir()
                                            print('isadirectory : {}'.format(isadirectory))

                                            #To get the extension of the file
                                            fileExtension = mypath/'data'/'fuel_econ.csv'
                                            print('File extension : {}'.format(filePath.suffix))


                                            OUTPUT:
                                            ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED



                                            Absolute path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2



                                            File path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2datafuel_econ.csv



                                            isfileExist : True



                                            isadirectory : False



                                            File extension : .csv






                                            share|improve this answer






























                                              0














                                              USEFUL PATH PROPERTIES IN PYTHON:



                                               from pathlib import Path

                                              #Returns the path of the directory, where your script file is placed
                                              mypath = Path().absolute()
                                              print('Absolute path : {}'.format(mypath))

                                              #if you want to go to any other file inside the subdirectories of the directory path got from above method
                                              filePath = mypath/'data'/'fuel_econ.csv'
                                              print('File path : {}'.format(filePath))

                                              #To check if file present in that directory or Not
                                              isfileExist = filePath.exists()
                                              print('isfileExist : {}'.format(isfileExist))

                                              #To check if the path is a directory or a File
                                              isadirectory = filePath.is_dir()
                                              print('isadirectory : {}'.format(isadirectory))

                                              #To get the extension of the file
                                              fileExtension = mypath/'data'/'fuel_econ.csv'
                                              print('File extension : {}'.format(filePath.suffix))


                                              OUTPUT:
                                              ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED



                                              Absolute path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2



                                              File path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2datafuel_econ.csv



                                              isfileExist : True



                                              isadirectory : False



                                              File extension : .csv






                                              share|improve this answer




























                                                0












                                                0








                                                0







                                                USEFUL PATH PROPERTIES IN PYTHON:



                                                 from pathlib import Path

                                                #Returns the path of the directory, where your script file is placed
                                                mypath = Path().absolute()
                                                print('Absolute path : {}'.format(mypath))

                                                #if you want to go to any other file inside the subdirectories of the directory path got from above method
                                                filePath = mypath/'data'/'fuel_econ.csv'
                                                print('File path : {}'.format(filePath))

                                                #To check if file present in that directory or Not
                                                isfileExist = filePath.exists()
                                                print('isfileExist : {}'.format(isfileExist))

                                                #To check if the path is a directory or a File
                                                isadirectory = filePath.is_dir()
                                                print('isadirectory : {}'.format(isadirectory))

                                                #To get the extension of the file
                                                fileExtension = mypath/'data'/'fuel_econ.csv'
                                                print('File extension : {}'.format(filePath.suffix))


                                                OUTPUT:
                                                ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED



                                                Absolute path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2



                                                File path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2datafuel_econ.csv



                                                isfileExist : True



                                                isadirectory : False



                                                File extension : .csv






                                                share|improve this answer















                                                USEFUL PATH PROPERTIES IN PYTHON:



                                                 from pathlib import Path

                                                #Returns the path of the directory, where your script file is placed
                                                mypath = Path().absolute()
                                                print('Absolute path : {}'.format(mypath))

                                                #if you want to go to any other file inside the subdirectories of the directory path got from above method
                                                filePath = mypath/'data'/'fuel_econ.csv'
                                                print('File path : {}'.format(filePath))

                                                #To check if file present in that directory or Not
                                                isfileExist = filePath.exists()
                                                print('isfileExist : {}'.format(isfileExist))

                                                #To check if the path is a directory or a File
                                                isadirectory = filePath.is_dir()
                                                print('isadirectory : {}'.format(isadirectory))

                                                #To get the extension of the file
                                                fileExtension = mypath/'data'/'fuel_econ.csv'
                                                print('File extension : {}'.format(filePath.suffix))


                                                OUTPUT:
                                                ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED



                                                Absolute path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2



                                                File path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2datafuel_econ.csv



                                                isfileExist : True



                                                isadirectory : False



                                                File extension : .csv







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Mar 10 at 17:21

























                                                answered Mar 10 at 4:06









                                                Arpan SainiArpan Saini

                                                428519




                                                428519























                                                    -1














                                                    ## IMPORT MODULES
                                                    import os

                                                    ## CALCULATE FILEPATH VARIABLE
                                                    filepath = os.path.abspath('') ## ~ os.getcwd()
                                                    ## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
                                                    ## ..OR DIFFERENT IN SOME CIRCUMSTANCES





                                                    share|improve this answer





















                                                    • 2





                                                      The current working directory might not be the same as the directory of the current file. Your solution will only work if the current working directory is the same as the directory that holds the file. That can be fairly common during development, but is usually pretty rare for a deployed script.

                                                      – Bryan Oakley
                                                      Jan 3 at 22:45











                                                    • Thanks for the info. I updated my answer to reflect the possibility that these may not be equivalent returning the same filepath. Such is reason why I adhere to philosophy of coding called "incremental programming", testing, and lots of print() function calls to test output and/or values return at each step of the way. I hope my code now better reflects the reality of os.path.abspath() vs. os.getcwd() since I do not claim to know everything. However you can see that I put os.getcwd() in comments as not the main solution, but rather as an alt piece of code worth remembering and checking.

                                                      – Jerusalem Programmer
                                                      Jan 6 at 8:45











                                                    • P.S. I think someone edited and erased the majority of my answer that I posted here... :( Such discourages people from participating if their answers are going to be censored and chopped.

                                                      – Jerusalem Programmer
                                                      Jan 6 at 8:49











                                                    • You're the only person to have edited this answer. Also, your edits still don't properly answer the question. The question is specifically asking about the path to the file's directory, and your answer only mentions getting the current directory. That is not a correct answer, since the current directory is very often not the same as the directory the script is in. This has nothing to do with abspath.

                                                      – Bryan Oakley
                                                      Jan 6 at 14:49













                                                    • Most certainly the code I shared gives path to the file's directory if run from the directory and/or file from where you want to know the absolute file path. Most certainly it is a correct answer. Please don't be a troll.

                                                      – Jerusalem Programmer
                                                      Jan 7 at 4:48
















                                                    -1














                                                    ## IMPORT MODULES
                                                    import os

                                                    ## CALCULATE FILEPATH VARIABLE
                                                    filepath = os.path.abspath('') ## ~ os.getcwd()
                                                    ## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
                                                    ## ..OR DIFFERENT IN SOME CIRCUMSTANCES





                                                    share|improve this answer





















                                                    • 2





                                                      The current working directory might not be the same as the directory of the current file. Your solution will only work if the current working directory is the same as the directory that holds the file. That can be fairly common during development, but is usually pretty rare for a deployed script.

                                                      – Bryan Oakley
                                                      Jan 3 at 22:45











                                                    • Thanks for the info. I updated my answer to reflect the possibility that these may not be equivalent returning the same filepath. Such is reason why I adhere to philosophy of coding called "incremental programming", testing, and lots of print() function calls to test output and/or values return at each step of the way. I hope my code now better reflects the reality of os.path.abspath() vs. os.getcwd() since I do not claim to know everything. However you can see that I put os.getcwd() in comments as not the main solution, but rather as an alt piece of code worth remembering and checking.

                                                      – Jerusalem Programmer
                                                      Jan 6 at 8:45











                                                    • P.S. I think someone edited and erased the majority of my answer that I posted here... :( Such discourages people from participating if their answers are going to be censored and chopped.

                                                      – Jerusalem Programmer
                                                      Jan 6 at 8:49











                                                    • You're the only person to have edited this answer. Also, your edits still don't properly answer the question. The question is specifically asking about the path to the file's directory, and your answer only mentions getting the current directory. That is not a correct answer, since the current directory is very often not the same as the directory the script is in. This has nothing to do with abspath.

                                                      – Bryan Oakley
                                                      Jan 6 at 14:49













                                                    • Most certainly the code I shared gives path to the file's directory if run from the directory and/or file from where you want to know the absolute file path. Most certainly it is a correct answer. Please don't be a troll.

                                                      – Jerusalem Programmer
                                                      Jan 7 at 4:48














                                                    -1












                                                    -1








                                                    -1







                                                    ## IMPORT MODULES
                                                    import os

                                                    ## CALCULATE FILEPATH VARIABLE
                                                    filepath = os.path.abspath('') ## ~ os.getcwd()
                                                    ## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
                                                    ## ..OR DIFFERENT IN SOME CIRCUMSTANCES





                                                    share|improve this answer















                                                    ## IMPORT MODULES
                                                    import os

                                                    ## CALCULATE FILEPATH VARIABLE
                                                    filepath = os.path.abspath('') ## ~ os.getcwd()
                                                    ## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
                                                    ## ..OR DIFFERENT IN SOME CIRCUMSTANCES






                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Jan 6 at 8:47

























                                                    answered Jan 2 at 13:13









                                                    Jerusalem ProgrammerJerusalem Programmer

                                                    162212




                                                    162212








                                                    • 2





                                                      The current working directory might not be the same as the directory of the current file. Your solution will only work if the current working directory is the same as the directory that holds the file. That can be fairly common during development, but is usually pretty rare for a deployed script.

                                                      – Bryan Oakley
                                                      Jan 3 at 22:45











                                                    • Thanks for the info. I updated my answer to reflect the possibility that these may not be equivalent returning the same filepath. Such is reason why I adhere to philosophy of coding called "incremental programming", testing, and lots of print() function calls to test output and/or values return at each step of the way. I hope my code now better reflects the reality of os.path.abspath() vs. os.getcwd() since I do not claim to know everything. However you can see that I put os.getcwd() in comments as not the main solution, but rather as an alt piece of code worth remembering and checking.

                                                      – Jerusalem Programmer
                                                      Jan 6 at 8:45











                                                    • P.S. I think someone edited and erased the majority of my answer that I posted here... :( Such discourages people from participating if their answers are going to be censored and chopped.

                                                      – Jerusalem Programmer
                                                      Jan 6 at 8:49











                                                    • You're the only person to have edited this answer. Also, your edits still don't properly answer the question. The question is specifically asking about the path to the file's directory, and your answer only mentions getting the current directory. That is not a correct answer, since the current directory is very often not the same as the directory the script is in. This has nothing to do with abspath.

                                                      – Bryan Oakley
                                                      Jan 6 at 14:49













                                                    • Most certainly the code I shared gives path to the file's directory if run from the directory and/or file from where you want to know the absolute file path. Most certainly it is a correct answer. Please don't be a troll.

                                                      – Jerusalem Programmer
                                                      Jan 7 at 4:48














                                                    • 2





                                                      The current working directory might not be the same as the directory of the current file. Your solution will only work if the current working directory is the same as the directory that holds the file. That can be fairly common during development, but is usually pretty rare for a deployed script.

                                                      – Bryan Oakley
                                                      Jan 3 at 22:45











                                                    • Thanks for the info. I updated my answer to reflect the possibility that these may not be equivalent returning the same filepath. Such is reason why I adhere to philosophy of coding called "incremental programming", testing, and lots of print() function calls to test output and/or values return at each step of the way. I hope my code now better reflects the reality of os.path.abspath() vs. os.getcwd() since I do not claim to know everything. However you can see that I put os.getcwd() in comments as not the main solution, but rather as an alt piece of code worth remembering and checking.

                                                      – Jerusalem Programmer
                                                      Jan 6 at 8:45











                                                    • P.S. I think someone edited and erased the majority of my answer that I posted here... :( Such discourages people from participating if their answers are going to be censored and chopped.

                                                      – Jerusalem Programmer
                                                      Jan 6 at 8:49











                                                    • You're the only person to have edited this answer. Also, your edits still don't properly answer the question. The question is specifically asking about the path to the file's directory, and your answer only mentions getting the current directory. That is not a correct answer, since the current directory is very often not the same as the directory the script is in. This has nothing to do with abspath.

                                                      – Bryan Oakley
                                                      Jan 6 at 14:49













                                                    • Most certainly the code I shared gives path to the file's directory if run from the directory and/or file from where you want to know the absolute file path. Most certainly it is a correct answer. Please don't be a troll.

                                                      – Jerusalem Programmer
                                                      Jan 7 at 4:48








                                                    2




                                                    2





                                                    The current working directory might not be the same as the directory of the current file. Your solution will only work if the current working directory is the same as the directory that holds the file. That can be fairly common during development, but is usually pretty rare for a deployed script.

                                                    – Bryan Oakley
                                                    Jan 3 at 22:45





                                                    The current working directory might not be the same as the directory of the current file. Your solution will only work if the current working directory is the same as the directory that holds the file. That can be fairly common during development, but is usually pretty rare for a deployed script.

                                                    – Bryan Oakley
                                                    Jan 3 at 22:45













                                                    Thanks for the info. I updated my answer to reflect the possibility that these may not be equivalent returning the same filepath. Such is reason why I adhere to philosophy of coding called "incremental programming", testing, and lots of print() function calls to test output and/or values return at each step of the way. I hope my code now better reflects the reality of os.path.abspath() vs. os.getcwd() since I do not claim to know everything. However you can see that I put os.getcwd() in comments as not the main solution, but rather as an alt piece of code worth remembering and checking.

                                                    – Jerusalem Programmer
                                                    Jan 6 at 8:45





                                                    Thanks for the info. I updated my answer to reflect the possibility that these may not be equivalent returning the same filepath. Such is reason why I adhere to philosophy of coding called "incremental programming", testing, and lots of print() function calls to test output and/or values return at each step of the way. I hope my code now better reflects the reality of os.path.abspath() vs. os.getcwd() since I do not claim to know everything. However you can see that I put os.getcwd() in comments as not the main solution, but rather as an alt piece of code worth remembering and checking.

                                                    – Jerusalem Programmer
                                                    Jan 6 at 8:45













                                                    P.S. I think someone edited and erased the majority of my answer that I posted here... :( Such discourages people from participating if their answers are going to be censored and chopped.

                                                    – Jerusalem Programmer
                                                    Jan 6 at 8:49





                                                    P.S. I think someone edited and erased the majority of my answer that I posted here... :( Such discourages people from participating if their answers are going to be censored and chopped.

                                                    – Jerusalem Programmer
                                                    Jan 6 at 8:49













                                                    You're the only person to have edited this answer. Also, your edits still don't properly answer the question. The question is specifically asking about the path to the file's directory, and your answer only mentions getting the current directory. That is not a correct answer, since the current directory is very often not the same as the directory the script is in. This has nothing to do with abspath.

                                                    – Bryan Oakley
                                                    Jan 6 at 14:49







                                                    You're the only person to have edited this answer. Also, your edits still don't properly answer the question. The question is specifically asking about the path to the file's directory, and your answer only mentions getting the current directory. That is not a correct answer, since the current directory is very often not the same as the directory the script is in. This has nothing to do with abspath.

                                                    – Bryan Oakley
                                                    Jan 6 at 14:49















                                                    Most certainly the code I shared gives path to the file's directory if run from the directory and/or file from where you want to know the absolute file path. Most certainly it is a correct answer. Please don't be a troll.

                                                    – Jerusalem Programmer
                                                    Jan 7 at 4:48





                                                    Most certainly the code I shared gives path to the file's directory if run from the directory and/or file from where you want to know the absolute file path. Most certainly it is a correct answer. Please don't be a troll.

                                                    – Jerusalem Programmer
                                                    Jan 7 at 4:48


















                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3430372%2fhow-to-get-full-path-of-current-files-directory-in-python%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    MongoDB - Not Authorized To Execute Command

                                                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                                    How to fix TextFormField cause rebuild widget in Flutter