Directories in Wolfram Language

Here’s an idiomatic Wolfram Language example that demonstrates working with directories:

(* Working with Directories in Wolfram Language *)

(* Create a new subdirectory in the current working directory *)
CreateDirectory["subdir"]

(* Helper function to create an empty file *)
createEmptyFile[name_] := Export[name, ""]

(* Create some files and directories *)
createEmptyFile["subdir/file1.txt"]
CreateDirectory["subdir/parent/child"]
createEmptyFile["subdir/parent/file2.txt"]
createEmptyFile["subdir/parent/file3.txt"]
createEmptyFile["subdir/parent/child/file4.txt"]

(* List contents of a directory *)
Print["Listing subdir/parent:"]
FileNames[All, "subdir/parent"]

(* Change current working directory *)
SetDirectory["subdir/parent/child"]

(* List contents of current directory *)
Print["Listing current directory:"]
FileNames[]

(* Change back to original directory *)
ResetDirectory[]

(* Recursively list all files and directories *)
Print["Visiting subdir recursively:"]
FileNames["*", "subdir", Infinity]

(* Clean up: remove the created directory and its contents *)
DeleteDirectory["subdir", DeleteContents -> True]

This Wolfram Language code demonstrates various operations for working with directories:

  1. We use CreateDirectory to create new directories.

  2. The createEmptyFile function uses Export to create empty files.

  3. FileNames is used to list directory contents. When called without arguments, it lists the current directory.

  4. SetDirectory changes the current working directory, similar to cd in shell commands.

  5. ResetDirectory returns to the previous working directory.

  6. FileNames with the Infinity option recursively lists all files and subdirectories.

  7. DeleteDirectory with the DeleteContents -> True option removes a directory and all its contents.

To run this code:

  1. Copy the code into a notebook in Wolfram Desktop or Mathematica.
  2. Evaluate the entire notebook or individual cells.

The output will show the directory listings and the recursive visit of the created directory structure.

Note that Wolfram Language provides high-level functions for file and directory operations, making it easy to work with the file system in a platform-independent manner. Unlike languages that require explicit error handling, Wolfram Language will automatically throw exceptions if operations fail, which can be caught using Check or Quiet if needed.