Mathematica 教程 函数 »| 教程 »|更多关于 »

# Naming and Finding Files

## Directory Operations

The precise details of the naming of files differ from one computer system to another. Nevertheless, Mathematica provides some fairly general mechanisms that work on all systems.
Mathematica assumes that all your files are arranged in a hierarchy of directories. To find a particular file, Mathematica must know both what the name of the file is, and what sequence of directories it is in.
At any given time, however, you have a current working directory, and you can refer to files or other directories by specifying where they are relative to this directory. Typically you can refer to files or directories that are actually in this directory simply by giving their names, with no directory information.
 Directory[] your current working directory SetDirectory["dir"] set your current working directory ResetDirectory[] revert to your previous working directory

Manipulating directories.

This gives a string representing your current working directory.
 Out[1]=
This sets your current working directory to be the Examples subdirectory.
 Out[2]=
Now your current working directory is different.
 Out[3]=
This reverts to your previous working directory.
 Out[4]=
When you call SetDirectory, you can give any directory name that is recognized by your operating system. Thus, for example, on Unix-based systems, you can specify a directory one level up in the directory hierarchy using the notation .., and you can specify your "home" directory as ~.
Whenever you go to a new directory using SetDirectory, Mathematica always remembers what the previous directory was. You can return to this previous directory using ResetDirectory. In general, Mathematica maintains a stack of directories, given by . Every time you call SetDirectory, it adds a new directory to the stack, and every time you call ResetDirectory it removes a directory from the stack.
 ParentDirectory[] the parent of your current working directory \$InitialDirectory the initial directory when Mathematica was started \$HomeDirectory your home directory, if this is defined \$BaseDirectory the base directory for systemwide files to be loaded by Mathematica \$UserBaseDirectory the base directory for user-specific files to be loaded by Mathematica \$InstallationDirectory the top-level directory in which your Mathematica installation resides

Special directories.

## Finding a File

Whenever you ask for a particular file, Mathematica in general goes through several steps to try and find the file you want. The first step is to use whatever standard mechanisms exist in your operating system or shell.
Mathematica scans the full name you give for a file, and looks to see whether it contains any of the "metacharacters" *, \$, ~, ?, [, ", \ and '. If it finds such characters, then it passes the full name to your operating system or shell for interpretation. This means that if you are using a Unix-based system, then constructions like name* and \$VAR will be expanded at this point. But in general, Mathematica takes whatever was returned by your operating system or shell, and treats this as the full file name.
For output files, this is the end of the processing that Mathematica does. If Mathematica cannot find a unique file with the name you specified, then it will proceed to create the file.
If you are trying to get input from a file, however, then there is another round of processing that Mathematica does. What happens is that Mathematica looks at the value of the Path option for the function you are using to determine the names of directories relative to which it should search for the file. The default setting for the Path option is the global variable \$Path.
 Get["file",Path->{"dir1","dir2",...}] get a file, searching for it relative to the directories diri \$Path default list of directories relative to which to search for input files

Search path for files.

In general, the global variable \$Path is defined to be a list of strings, with each string representing a directory. Every time you ask for an input file, what Mathematica effectively does is temporarily to make each of these directories in turn your current working directory, and then from that directory to try and find the file you have requested.
Here is a typical setting for \$Path. The current directory (.) and your home directory (~) are listed first.
 Out[5]=
You can also use FindFile to locate a file.
 FindFile["name"] find the file with the specified name that would be loaded by Get and related functions FileExistsQ["name"] determine whether the file exists

Finding a file on the \$Path.

FindFile searches all directories in \$Path and returns the absolute name of the file that would be loaded by Get, Needs, and other functions. FileExistsQ tests whether the file with the given name exists.
 Out[5]=
FindFile applied to a package name returns the absolute name of the init.m file from that package.
 Out[5]=

## Listing Contents of Directories

 FileNames[] list all files in your current working directory FileNames["form"] list all files in your current working directory whose names match the string pattern form FileNames[{"form1","form2",...}] list all files whose names match any of the formi FileNames[forms,{"dir1","dir2",...}] give the full names of all files whose names match forms in any of the directories diri FileNames[forms,dirs,n] include files that are in subdirectories up to n levels down FileNames[forms,dirs,Infinity] include files in all subdirectories FileNames[forms,\$Path,Infinity] give all files whose names match forms in any subdirectory of the directories in \$Path

Getting lists of files in particular directories.

FileNames returns a list of strings corresponding to file names. When it returns a file that is not in your current directory, it gives the name of the file relative to the current directory. Note that all names are given in the format appropriate for the particular computer system on which they were generated.
Here is a list of all files in the current working directory whose names end with .m.
 Out[6]=
 Out[7]=
The file name form you give to FileNames can use any of Mathematica's string pattern objects, typically combined with the ~~ operator.
This gives a list of all files in your current working directory whose names match the form Test*.m.
 Out[3]=
This lists only those files with names of the form Test d.m, where d is a sequence of one or more digits.
 Out[3]=

## Composing a Filename

 DirectoryName["file"] extract the directory name from a file name ToFileName["directory","name"] assemble a full file name from a directory name and a file name ParentDirectory["directory"] give the parent of a directory ToFileName[{"dir1","dir2",...},"name"] assemble a full file name from a hierarchy of directory names ToFileName[{"dir1","dir2",...}] assemble a single directory name from a hierarchy of directory names

Manipulating file names.

You should realize that different computer systems may give file names in different ways. Thus, for example, Windows systems typically give names in the form dir:\dir\dir\name and Unix systems give names in the form dir/dir/name. The function ToFileName assembles file names in the appropriate way for the particular computer system you are using.
This gives the directory portion of the file name.
 Out[8]=
This constructs the full name of another file in the same directory as test.m.
 Out[9]=
 FileNameSplit["name"] split the file name into a list of directory and file names FileNameJoin[{dir1,...}] combine a list of directory and file names into the file name FileNameTake["name",...] extract part of the file name FileNameDrop["name",...] drop parts of the file name FileNameDepth["name"] get the number of path elements in the file name \$PathnameSeparator path name separator used in your operating system

Manipulating file names.

Functions like FileNameSplit and FileNameJoin provide additional operations on file names. They respect the file name separator used by your operating system and will split the file name appropriately. FileNameJoin will by default use the \$PathnameSeparator to produce the name in a canonical form suitable for your operating system.
If you want to set up a collection of related files, it is often convenient to be able to refer to one file when you are reading another one. The global variable \$Input gives the name of the file from which input is currently being taken. Using DirectoryName and ToFileName you can then conveniently specify the names of other related files.
 \$Input the name of the file or stream from which input is currently being taken

Finding out how to refer to a file currently being read by Mathematica.

One issue in handling files in Mathematica is that the form of file and directory names varies between computer systems. This means for example that names of files which contain standard Mathematica packages may be quite different on different systems. Through a sequence of conventions, it is however possible to read in a standard Mathematica package with the same command on all systems. The way this works is that each package defines a so-called Mathematica context, of the form name`name`. On each system, all files are named in correspondence with the contexts they define. Then when you use the command <<name`name` Mathematica automatically translates the context name into the file name appropriate for your particular computer system.

## Standard Filename Extensions

 file.m Mathematica expression file in plain text format file.nb Mathematica notebook file file.mx Mathematica definitions in DumpSave format

Typical names of Mathematica files.

If you use a notebook interface to Mathematica, then the Mathematica front end allows you to save complete notebooks, including not only Mathematica input and output, but also text, graphics and other material.
It is conventional to give Mathematica notebook files names that end in .nb, and most versions of Mathematica enforce this convention.
 FileBaseName["name"] the parent of your current working directory FileExtension["name"] the initial directory when Mathematica was started

File name and extension.

You can use FileBaseName and FileExtension to extract the name of the file and its extension.
When you open a notebook in the Mathematica front end, Mathematica will immediately display the contents of the notebook, but it will not normally send any of these contents to the kernel for evaluation until you explicitly request this to be done.
Within a Mathematica notebook, however, you can use the Cell menu in the front end to identify certain cells as initialization cells, and if you do this, then the contents of these cells will automatically be evaluated whenever you open the notebook.
 The I in the cell bracket indicates that the second cell is an initialization cell that will be evaluated whenever the notebook is opened.
It is sometimes convenient to maintain Mathematica material both in a notebook which contains explanatory text, and in a package which contains only raw Mathematica definitions. You can do this by putting the Mathematica definitions into initialization cells in the notebook. Every time you save the notebook, the front end will then allow you to save an associated .m file which contains only the raw Mathematica definitions.