Pytest doesn't see a data file from the source folder

Question:

I have the following folder structure:

enter image description here

main.py

import pandas as pd

data = pd.read_csv('data.csv')

def add_num_to_env_num():
    print("success")

test_main.py

import sys
sys.path.insert(1, '/src')

import src.main as main


def test_add_num_to_env_num():
    main.add_num_to_env_num()

When I run command python -m pytest I get the following error:

ERROR tests/test_main.py - FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'

I hoped that the line: sys.path.insert(1, '/src') will solve the issue but it didn’t. How can I solve the issue?

EDIT: for the real use-case I cannot use absolute paths.

Asked By: Roberto

||

Answers:

Assuming that data.csv will always be in the same directory, you can write main.py to always load data.csv with a path relative to the location of main.py. The __file__ variable contains the full path of the script currently being executed/imported, so we can get the relative path from that.

This solution uses pathlib.Path, but it is possible with only the tools in the os module as well.

Having a separate datapath variable here isn’t necessary, but added for readability.


import pandas as pd
from pathlib import Path

datapath = Path(__file__).parent / Path("data.csv")
data = pd.read_csv(datapath)

def add_num():
    return 1

This related question has multiple answers of other ways to get the script’s parent directory and relative path.
How do I get the path and name of the file that is currently executing?

Answered By: nigh_anxiety
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.