Importing and Exporting Files
| Import["file","List"] | import a one-dimensional list of data from a file |
| Export["file",list,"List"] | export list to a file as a one-dimensional list of data |
| Import["file","Table"] | import a two-dimensional table of data from a file |
| Export["file",list,"Table"] | export list to a file as a two-dimensional table of data |
| Import["file","CSV"] | import data in comma-separated format |
| Export["file",list,"CSV"] | export data in comma-separated format |
Importing and exporting lists and tables of data.
This exports a list of data to the file out1.
| Out[1]= |  |
|
Here are the contents of the file. |
This imports the contents back into Mathematica.
| Out[3]= |  |
|
If you want to use data purely within
Mathematica, then the best way to keep it in a file is usually as a complete
Mathematica expression, with all its structure preserved, as discussed in
"Reading and Writing Mathematica Files: Files and Streams". But if you want to exchange data with other programs, it is often more convenient to have the data in a simple list or table format.
This exports a two-dimensional array of data.
| Out[4]= |  |
|
When necessary, numbers are written in C or Fortran-like "E" notation. |
This imports the array back into Mathematica.
| Out[6]= |  |
|
If you have a file in which each line consists of a single number, then you can use
Import["file", "List"] to import the contents of the file as a list of numbers. If each line consists of a sequence of numbers separated by tabs or spaces, then
Import["file", "Table"] will yield a list of lists of numbers. If the file contains items that are not numbers, then these are returned as
Mathematica strings.
This exports a mixture of textual and numerical data.
| Out[7]= |  |
|
Here is the exported data. |
This imports the data back into Mathematica.
| Out[9]= |  |
|
With InputForm, you can explicitly see the strings.
Out[10]//InputForm= |
| |  |
|
| Import["file","List"] | treat each line as a separate numerical or other data item |
| Import["file","Table"] | treat each element on each line as a separate numerical or other data item |
| Import["file","String"] | treat the whole file as a single character string |
| Import["file","Text"] | treat the whole file as a single string of text |
| Import["file",{"Text","Lines"}] | treat each line as a string of text |
| Import["file",{"Text","Words"}] | treat each separated word as a string of text |
Importing files in different formats.
This creates a file with two lines of text.
| Out[11]= |  |
|
Here are the contents of the file. |
This imports the whole file as a single string.
Out[13]//InputForm= |
| |  |
|
This imports the file as a list of lines of text.
Out[14]//InputForm= |
| |  |
|
This imports the file as a list of words separated by white space.
Out[15]//InputForm= |
| |  |
|