1.11.2 Advanced Topic: Finding and Manipulating Files
Although the details of how files are named and organized differ from one computer system to another, Mathematica provides some fairly general mechanisms for finding and handling files.
Mathematica assumes that files on your computer system are organized in a collection of directories. At any point, you have a current working directory. You can always refer to files in this directory just by giving their names.
Functions for finding and manipulating files.
|Directory[ ] ||give your current working directory |
|SetDirectory["dir"] ||set your current working directory |
|FileNames[ ] ||list the files in your current working directory |
|FileNames["form"] ||list the files whose names match a certain form |
|<<name ||read in a file with the specified name |
|<<context` ||read in a file corresponding to the specified context |
|CopyFile["", ""] ||copy to |
|DeleteFile["file"] ||delete a file |
|This is the current working directory. The form it has differs from one computer system to another. || |
|This resets the current working directory. || |
|This gives a list of all files in your current working directory whose names match the form Test*.m. || |
Although you usually want to create files only in your current working directory, you often need to read in files from other directories. As a result, when you ask Mathematica to read in a file with a particular name, Mathematica automatically searches a list of directories (specified by the value of the search path variable $Path) to try and find a file with that name.
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.
Searching for text in files.
|FindList["file", "text"] ||give a list of all lines in a file that contain the specified text |
|FindList[FileNames[ ], "text"] ||search in all files in your current directory |
|This searches for all lines in the file BookIndex containing diagrams. || |