Search code examples
pythonpathpycharm

How to set working directory for projects in PyCharm?


I'm unable to use relative paths in my code while using PyCharm. For instance, a simple open('test.txt', 'r') will not work - whereupon I am sure the file exists in the same level as the running py file. PyCharm will return this error.

FileNotFoundError: [Errno 2] No such file or directory:

After reading answers online on Stack Overflow, I have tried multiple options including:

  • Changing test.txt to ./test.txt
  • Closing project, deleting the .idea folder, open the folder with code.
  • Reinstalling as well as installing the latest version of PyCharm.
  • Invalidating caches and restarting.

None of these options have worked for me. Is there someway I can tell PyCharm to refresh the current working directory (or even to see where it thinks the current working directory is)?

Running the script in a terminal window will work. This appears to be a problem with PyCharm and not the script.


Solution

  • I have Pycharm 4.5, so things might have changed a bit.

    Try going to Settings > Project > Project Structure

    On this dialog, click your folder that has the source code in it, and then click the blue folder in the menu to note it as "source" folder. I believe this fixes a lot of the path issues in Pycharm

    Here is the link to "content roots": https://www.jetbrains.com/pycharm/help/content-root.html