Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm current working directory

Recently, 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 StackOverflow, 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)?

Thanks in advance!

Edit: I should note that running the script in a terminal window will work. This appears to be a problem with PyCharm and not the script.

like image 786
qwertyuip9 Avatar asked Dec 16 '15 04:12

qwertyuip9


People also ask

How do I get the current working directory in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

How do I find my current working directory?

Get the current working directory: os. os. getcwd() returns the absolute path of the current working directory where Python is running as a string str . getcwd stands for "get current working directory", and the Unix command pwd stands for "print working directory".

How do I change the default working directory in PyCharm?

button in the submenu appearing when clicking on your currently selected run configuration in the top right of PyCharm, you are able to edit the fields (and therefore also the working directory) of Python run configurations by selecting Python from the Templates (also called Defaults in versions pre-2018) and ...


3 Answers

Change: Run > Edit Configurations > Working directory, which sets the working directory for a specific project. (This is on a Mac)

like image 195
andere Avatar answered Oct 08 '22 22:10

andere


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

like image 44
Dan Avatar answered Oct 08 '22 22:10

Dan


Current version 2019.2 somehow ignores "source root" from the "project structure". Here's how to actually enforce it:

Run -> Edit Configurations -> Python -> "Edit Templates" this buttin -> fill out "Working Directory"

like image 10
Ufos Avatar answered Oct 08 '22 21:10

Ufos