Incorrect path with function getcwd()


I get the wrong path back. The Datafile is in D:… and get everytime the path C:Python27libsite-packagesxy back from python. I use the function

path = getcwd()

How can I fix it?

Asked By: A.Boss



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
Answered By: order

In my idea, make sure your IDE has your target directory opened as your project folder.
After all, it’s a debug-time error, and won’t affect the smooth running of your program in the runtime, if your program’s launch script has the right address for your program to run, and does its part normally!
By the way @order, I’m totally against hardcoding a path into your code, because it’s just a very lame programming exercise!
Just get yourselves used to going through the right exercise, although it doesn’t seem very beneficial in the short run. in the coming years of your career, you’re going to be against using the cons and pros of such a comparison, but it will become a right or wrong coding exercise!

Answered By: Reza SA
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.