Search code examples
pythonpathgetcwd

Incorrect path with function getcwd()


I get the wrong path back. The Datafile is in D:... and get everytime the path C:\Python27\lib\site-packages\xy back from python. I use the function

path = getcwd()

How can I fix it?


Solution

  • You may be executing the script in a different place than your intended directory.

    Solution 1: Move the .py file to the target directory, and execute it there.

    • Pros:
      • Easy
      • Works cross-platform (and for other users - if you do this, use getcwdu for Unicode)
      • No hard-coded path strings
    • Cons:
      • File must be in the same or higher directory as target folder

    Solution 2: Manually write the string of the path to the folder.

    • Pros:
      • 'Just Works'
    • Cons:
      • Annoying bugs w/typos
      • Need to re-code every time you change directories
      • Won't work anywhere else