0

I've cloned a copy of "machine_learning_examples" from GitHub (https://github.com/lazyprogrammer/machine_learning_examples). In it, it has a file "data_2d.csv" under the "linear_regression_class" folder.

I've added reference in my project to the "machine_learning_examples" project, and have tried a "from" and "import" statement with different target text, but can't determine the syntax to reference the "data_2d.csv" file.

I've been able to copy the csv file locally to a folder in my project and then just take the example code and modify the target:

import numpy as np

X = []

for line in open('data/data_2d.csv'):
    row = line.split(',')
    sample = list(map(float, row))
    X.append(sample)


X = np.array(X)
print(X)

This works ok, as expected. But, I would like to directly reference the csv as it exists in the cloned project.

Michael James
  • 492
  • 1
  • 6
  • 19
  • What is your project's path and where is the csv you want to import –  Aug 25 '18 at 23:30
  • Is your file downloaded to your computer? If it is, what is the path to file that you want to import? –  Aug 25 '18 at 23:33

2 Answers2

0

Try adding the csv directory to the Python path at runtime,

import sys
sys.path.append('/csvfilepath')
AYA
  • 917
  • 6
  • 7
0

If your file is downloaded in your computer, you must include the relative (or absolute) path to file, and you must check if the Python script has permissions to read it. If you include a relative path, that is always read in relation to the file that is being executed. If you import various modules, I recommend setting an absolute path to your directory base and use os.join to avoid incoherences related to the place where you run the script.

If the file is not in your computer, this is, in the internet (no matter if it is in a repo of your own or in a forked repo --or evenin a private VPS or in a WordPress site, for that matter), you can't load it into a Python script. You have to download it to a local directory and then open it.

Another option is to download it into a file-like object that is not stored in disk, but in memory (sort of a temporary download) and then delete the object after you are done with it. See here an example:

(edited example taken from Python - Download File Using Requests, Directly to Memory)

import io
import zipfile
from contextlib import closing
import requests # $ pip install requests

import csv

r = requests.get(url_to_file)
with closing(r), io.BytesIO(r.content) as archive:
    # do whatever you want with your archive
    # you can, for example, import it with csv
    reader = csv.reader(archive)
    # or
    writer = csv.writer(archive)

See https://docs.python.org/3/library/csv.html for csv documentation.