0

I'm trying to make parsing CSVs a little easier on me later down the road so I've created a small file to allow me to run parse_csv.toList('data.csv') and return a list to my script. Here is what the parse_csv.py imported file looks like:

parse_csv.py

import csv


def toList(file_location_name):
    result_list = []
    with open(file_location_name) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            result_list.append(row)
    return result_list

This is how I'm calling it in my scripts that are trying to utilize that file:

import-test.py

import parse_csv


print(
    parse_csv.toList('../data.csv')
)

I'm getting the following error when I run import-test.py:

Error

Traceback (most recent call last):
  File "{system path placeholder}\directory-test\import-test.py", line 5, in <module>
    parse_csv.toList('../data.csv')
  File "{system path placeholder}\parse_csv.py", line 6, in toList
    with open(file_location_name) as csv_file:
FileNotFoundError: [Errno 2] No such file or directory: '../data.csv'

My current project directory structure looks like this

Project
|
|--parse_csv.py
|--data.csv
|--directory-test
   |
   |--import-test.py

My first thought is that when I call open, '../data.csv' is being relatively referenced according to the parse_csv.py file instead of the intended import-test.py file.

I just want to make it so parse_csv.py can be imported anywhere and it will respect relative file paths in the calling file.

Please let me know if I need to be more clear. I know my wording may be confusing here.

Edit for clarity: The goal is to only call parse_csv.toList() and have it accept a string of a relative path to the file that called it.

Community
  • 1
  • 1
ExcellentSP
  • 1,529
  • 4
  • 15
  • 39

2 Answers2

0

You can have your parse_csv.toList function accept a file object instead of a file path. This way you open a file, give that to the module and it will work. Something like:

import parse_csv

with open('../data.csv') as csvFile:
    print(parse_csv.toList(csvFile))

Or you can convert the relative path to absolute path before call toList. Refer How to get an absolute file path in Python. It'll just add one extra line.

hoodakaushal
  • 1,253
  • 2
  • 16
  • 31
0

In import-test.py,

import os.path
import parse_csv

# to retrieve import-test.py's own absolute path
abs_path = os.path.abspath(__file__)

# its dir_path
dir_path = os.path.dirname(abs_path)

# data.csv's path
csv_path = os.path.join(dir_path, '..', 'data.csv')

# use the path
print(
    parse_csv.toList(csv_path)
)
ElpieKay
  • 27,194
  • 6
  • 32
  • 53