Quantcast
Channel: User Schwern - Stack Overflow
Viewing all articles
Browse latest Browse all 581

Answer by Schwern for Read same file from src and test in PyCharm

$
0
0

open('words.txt') looks for words.txt in the current directory. It will only work if you run board.py from src/scrabble. If it works when you run board.py directly in Pycharm, Pycharm must be setting the current working directory to src/scrabble. It will fall if you run, for example, python src/scrabble/board.py from the project root or anywhere else such as your testing directory.


os.path.realpath('words.txt') will not work for what you want. os.path.realpath will use the current working directory to make an absolute path. It will change if you change the directory you run the code from. For example, let's say we have this little program.

import osprint(os.path.realpath('words.txt'))

What we get depends on what directory we run it from.

PS C:\Users\Schwern> python tmp/test.pyC:\Users\Schwern\words.txtPS C:\Users\Schwern> cd .\tmp\PS C:\Users\Schwern\tmp> python test.py    C:\Users\Schwern\tmp\words.txt

Instead, make it into an absolute path using __file__. __file__ is the location of the file the code is in.

Use os.path.dirname to get the directory board.py is in from __file__. Then os.path.join that with words.txt to get an absolute path.

import osdir = os.path.dirname(__file__)words_file = os.path.join(dir, 'words.txt')print(words_file)

Now you get the same result no matter where you run from.

PS C:\Users\Schwern> python tmp/test.pyC:\Users\Schwern\tmp\words.txtPS C:\Users\Schwern> cd tmpPS C:\Users\Schwern\tmp> python test.py    C:\Users\Schwern\tmp\words.txt

Viewing all articles
Browse latest Browse all 581

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>