# How can I import a CSV file into Mathematica? [closed]

I have a data.csv file in the Downloads folder in my Macbook. I am trying to import the data into a Mathematica notebook using

gdoubleprime =  Import["data.csv", Path -> "Macintosh HD:\\Users\\gag\\Downloads"]


It gives me an error

Does anyone know why?

• If I had data.csv on my desktop on a Mac, I'd use Import["~/Desktop/data.csv"]. Hope this helps, read the docs. – user6014 Sep 4 at 0:42
• I'm not sure why no one said this, but  is not a valid path separator on macOS, nor is Macintosh HD: a valid prefix. Use /Users/gag/Downloads instead. That's all. – Szabolcs Sep 4 at 19:48

One way is gdoubleprime = Import["/Users/gag/Downloads/data.csv"]. However this will only work for the user gag. A more general way is to use the home directory and downloads with gdoubleprime = Import["~/Downloads/data.csv"].

You should also consider one of a couple of possible general policies for data files. The first is to put them into the same directory as the notebook, so that they move together and can be placed anywhere on your drive (or on any other operating system for that matter). You could then set the directory to the notebook directory and import from there:

SetDirectory[NotebookDirectory[]]
Import["data.csv"]


A variation on this that I use (perhaps overkill) looks like this:

SetDirectory[NotebookDirectory[]]
dataDir =  "../Curated Data";
nameS = “/replace_with_file_name_to_import";
extS = ".csv";
fileNameS = dataDir <> nameS <> extS
data=Import[fileNameS]


This allows you to have multiple MMA project directories all of which look into a single directory at the same level in the directory hierarchy which contains vetted data. The extension string is optional, but I sometimes have xls, csv, etc. files all with the same "left" name and this makes it a little less likely that I will confuse them since the extension string is explicit.

This is how I import files when I'm not sure of the path name. Open the terminal by typing command-Space then terminal. Then drag the file into the terminal window. You will see something like:

/Users/yourName/Documents/Papers/fileName.csv


Highlight this and copy paste into Mathematica:

data = Import["/Users/yourName/Documents/Papers/fileName.csv"]


and you will have all the information in the csv in the variable data.

• The menu item Insert -> File Path... is also handy in this scenario – user6014 Sep 4 at 1:33
• On Mac also useful is Command-Alt-C which copies the file path directly – b3m2a1 Sep 4 at 5:00

I recommend the use of FileNameJoin for dealing with OS full file path names. It is system indecent and you don't have to worry about such things as backslashing or directory name delimiters.

Both of the following work.

gdoubleprime = Import[FileNameJoin[{$HomeDirectory, "Downloads", "data.csv"}]]; gdoubleprime = Import["data.csv", Path -> FileNameJoin[{$HomeDirectory, "Downloads"}]];