How to | Input and Construct File Names in
Mathematica
Mathematica provides a simple and consistent method for accessing and using files. In addition to inserting a file path that is specific to your operating system,
Mathematica also allows programmatic construction of directory and file paths that are portable across different operating systems.
Mathematica lets you insert directory and file paths by typing them in directly, using the menu item, or with a keystroke-modified drag and drop. For information on these methods, see
How to: Insert a File Path.
You can also construct full file paths programmatically by using
FileNameJoin, or split file paths into their individual components with
FileNameSplit.
Any programs you write that use these functions are portable across operating systems, because they will use pathname separators and other conventions suitable for the current operating system.
If instead you were to use
StringSplit or
StringJoin to work with file names, you would need to manually replace the pathname separators and other file name conventions for each operating system you want your program to run on.
Use
FileNameJoin to construct a path for a hypothetical file on Windows:
| Out[5]= |  |
Do the same thing on a Macintosh:
| Out[10]= |  |
FileNameJoin also works with file paths that contain pathname separators:
| Out[19]= |  |
You do not have to provide a file for
FileNameJoin, since it also works with directories:
| Out[20]= |  |
FileNameJoin is very useful for constructing file names and paths based on
Mathematica system variables that represent certain directories.
Use
FileNameJoin with
$UserBaseDirectory to construct a file path for the kernel init.m file:
| Out[38]= |  |
Use
FileNameJoin with
$HomeDirectory to construct the

file path that was entered manually:
| Out[17]= |  |
Other commonly used
Mathematica system variables that represent directories are
$BaseDirectory,
$RootDirectory,
$HomeDirectory, and
$InstallationDirectory.
FileNameSplit is essentially the opposite of
FileNameJoin.
Use
FileNameSplit to split a file path into its components:
| Out[53]= |  |
Use
FileNameSplit to split
$UserBaseDirectory into its components. The first element of this list is an empty string. This represents the fact that
$UserBaseDirectory begins with a file name separator:
| Out[55]= |  |
| Out[1]= |  |
Use

(the short form of
Part) to get the first 4 directory components:
| Out[62]= |  |
Use
FileNameJoin to construct a directory path from these components by using

(which specifies the most recent output):
| Out[63]= |  |
You could also construct the same path by using
FileNameDrop:
| Out[66]= |  |
| Out[65]= |  |
Use
FileNameDrop to construct a path by getting rid of the last 3 directories in
$UserBaseDirectory:
| Out[67]= |  |