0

My question is similar to the one in link but with a slight difference

the project structure is

project_folder
--> main.py
--> scripts_folder
    --> script.py
--> data_folder
    --> data.csv

The main.py looks like this

from scripts_folder.script import a

a()

The script.py looks like this

import pandas as pd

df = pd.read_csv('../data_folder/data.csv')

# do some things with df


def a():
    print('something')

I am running main.py, which calls script.py, which has to import data from data.csv. I tried the method given in the question above. ie I tried importing using this line of code in scripty.py pd.reac_csv('../data_folder/data.csv') but it is not working.

It is giving me error

    handle = open(
FileNotFoundError: [Errno 2] No such file or directory: '../data_folder/data.csv'

[EDIT]

I tried moving the data.csv into scripts_folder as in

project_folder
--> main.py
--> scripts_folder
    --> script.py
    --> data.csv
--> data_folder (empty)

and I changed it to df = pd.read_csv('data.csv') and still I am getting the same error

    handle = open(
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'

Can someone help? Thanks

john wick
  • 73
  • 9
  • if you try using `import os print(os.getcwd())` wich is the output? Maybe the directory where you are executing is not the scripts_folder – Gam May 02 '22 at 09:18
  • Try "data_folder/data.csv" – Echo May 02 '22 at 10:06
  • @Gam I tried it on all the files in my project and I got the same directory. I tried using a relative path accordingly in pandas but it still gave error. – john wick May 02 '22 at 10:25
  • @Echo somehow that is working for the above case but for my real project, it is giving me the same error. I have no idea why. – john wick May 02 '22 at 10:27
  • The issue is with the relative path. From script.py try to print the current directory as mentioned by @Gam . You will get to know what the current path is and then give your path accordingly. – Echo May 02 '22 at 11:18
  • @johnwick wich directory is? As mentioned by @Echo the relative path must be given to accordingly to the current working directory. Maybe the interpreter starts with a completly differen working directory. Try open a terminal and execute: `cd "path_to_scripts_folder"` and then `python script.py`. Does this works (leaving your modifications as they are)? – Gam May 02 '22 at 12:38

1 Answers1

1
 handle = open(
FileNotFoundError: [Errno 2] No such file or directory: '../data_folder/data.csv'

This indicates that it supposed to work inside scripts_folder. ../data_folder means get the directory up relative to the current and find data_folder in this directory.

You could construct absolute file path for csv-file using os.path.abspath and os.path.join and give it to script reading data. To debug current working directory for script, use os.getcwd()

aestet
  • 314
  • 1
  • 3
  • 13