Change working directory when calling another script in Python

Question:

I have three files, base.py, read_a_file.py, and file_to_be_read.txt.
read_a_file.py contains the function read_file which opens
file_to_be_read.txt to be read. base.py imports read_a_file.py and calls the read_file function. I also have the following file structure:

-directory 
   -base.py
-read_a_file.py
-file_to_be_read.txt

The problem is that when I run base.py, I receive a FileNotFound error since the working directory is located at root/directory/ rather than at the root. I tried sys.path.append(root) but that didn’t seem to work. Any help would be appreciated!

Here’s the full traceback:

Error
Traceback (most recent call last):
  File "C:UsersagctutePycharmProjectssapaigenealgmyAItestsaitests.py", line 26, in test_AI
    self.ai = AI(player=Player())
  File "C:UsersagctutePycharmProjectssapaigenealgmyAIplayerai.py", line 24, in __init__
    self.tier_list = read_tier_list()
  File "C:UsersagctutePycharmProjectssapaigenealgmyAIstat_comparison.py", line 47, in read_tier_list
    with open('stat_tier_list.txt', 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'stat_tier_list.txt'
Asked By: agctute

||

Answers:

You identified the problem correctly but you are searching for the wrong answer. In most cases it is not a good idea to fiddle around with the working directory. If this is done at multiple occasions, you might end up in a place you did not expect.

You run into your problem because your script failed to find a file. This is because you hard-coded the path to it. Something like

with open('stat_tier_list.txt', 'r') as f:

can hardly be good idea. Use

path_to_file = 'stat_tier_list.txt'
with open(path_to_file , 'r') as f:

instead. This way you can make the path an argument of your function

# read_a_file.py
def read_file(path_to_file):
    with open(path_to_file, 'r') as f:

Now, go back to base.py and call the function properly:

# base.py
from pathlib import Path
from read_a_file import read_file # You may have to reorganise your folder structure to make this work

PATH_ROOT = Path('C:UsersCharles YoungPycharmProjectssapaigenealg')

path_to_file = PATH_ROOT.joinpath('file_to_be_read.txt')

read_a_file(path_to_file)

I suppose, that is what you really want. A function read_a_file should always accept an argument which specifies what file has to be read.

Answered By: Durtal