Home > Blockchain >  Is there a way to read data from csv using numpy.genfromtxt from a given directory?
Is there a way to read data from csv using numpy.genfromtxt from a given directory?

Time:09-29

I'm supposed to read in a csv filepath through argparse. So path of a csv file is args.X for example, how do I go about loading this data into a 2d numpy array? For now I was using Data = np.genfromtxt(args.X, delimiter=","), this works when args.X contains the file name instead of path and the file is in same folder as the python script. How do I read when the data is not in the same folder and I have been given a path instead to the file?

CodePudding user response:

It looks like you are having problems with backslashes disappearing, which is odd. Regardless, you're probably better off telling argparse you want a Path object (and using one). You probably want code something like this:

import numpy as np
from pathlib import Path
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("IN", type=Path)
parser.parse_args()

inf = args.IN.expanduser().resolve()
if not inf.exists():
    raise FileNotFoundError(f"No such file: {inf}")
Data = np.genfromtxt(inf, delimiter=",")
  • Related