3

I'm using Pycharm on OS X.

The structure is:

/Project
 /src
  codeA.py
  codeB.py
 /Data
  data.txt

src is marked as Sources Root and Data is marked as Resource root.

The problem is if I write in codeA.py

import codeB
with open("./Data/data.txt",'r'):
    pass

If I

  1. Execute code line by line in console, the file can be found.

  2. Execute by clicking "Run code.py" I'll get No Such File error.

  3. Execute codeA.py in terminal, I can not even import codeB.

If I write ../Data/data.txt instead, then method 2 can run but method 1 will get No Such File Error.

I've checked project interpreter path and console path. They are the same.

Any idea to solve this problem?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
spacegoing
  • 5,056
  • 5
  • 25
  • 42
  • 1
    Don't use raw relative path, you can get current file path with `__file__` and work out your path to `data.txt` from it. That will allow you to run your project from anywhere without having to worries about paths. – Cyrbil Jan 05 '16 at 11:16
  • @Cyrbil Nice suggestion! Many thanks for that. But I still want to know why I run into that problem :P – spacegoing Jan 05 '16 at 11:21

1 Answers1

4

Pycharm's console will include project root to PYTHONPATH. You can see and set this in Settings > Build, Execution, Deployment > Console > Python Console.

Your run config is probably wrong, ensure the working directory is correct, and that Add content/source roots to PYTHONPATH checkboxes are checked.

enter image description here

To avoid any path problem, it is advised to work with absolute path:

# get project path from main entry file
file_path = os.path.dirname(os.path.abspath(__file__))
project_path = os.path.abspath(os.path.join(file_path, os.path.pardir))

data_path = os.path.join(project_path, 'Data/data.txt')
Cyrbil
  • 6,341
  • 1
  • 24
  • 40
  • This solves the problem perfectly. But since `__file__` can only be used when the whole file is executed. What should I use when I'm developing the code in Ipython Console? – spacegoing Jan 05 '16 at 12:36
  • You can run `iPython` in the correct path, or [change current path programmatically](http://stackoverflow.com/a/8248430/956660). – Cyrbil Jan 05 '16 at 12:41