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?
Asked
Active
Viewed 155 times
1

Amit Kumar
- 25
- 3
-
Does it throw any error? Is it `FileNotFoundError` – Anwarvic Sep 28 '21 at 15:42
-
my path is D:\Amit\ell409\2019anz1787\gaussian.csv which i give as input, and the error is "D:Amitell4092019anz1787gaussian.csv not found" – Amit Kumar Sep 28 '21 at 15:44
-
That's not a valid path in Windows... I think you meant `D:\\Amitell4092019anz1787gaussian.csv ` right? – Anwarvic Sep 28 '21 at 15:45
-
*all* the backslashes are getting killed. I'll update my answer – 2e0byo Sep 28 '21 at 15:45
1 Answers
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
-
-
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