1

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?

Amit Kumar
  • 25
  • 3

1 Answers1

1

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=",")
2e0byo
  • 5,305
  • 1
  • 6
  • 26
  • thank you! this works – Amit Kumar Sep 28 '21 at 15:49
  • feel free to accept if it does :) As a shot in the dark I think some string escaping was going wrong, as you were missing *any* slashes in the error message. But in general use Path for paths, it's *much* easier – 2e0byo Sep 28 '21 at 15:54
  • yes turns out the slashes were being discarded as a result of some escape sequence – Amit Kumar Sep 28 '21 at 15:59