Function Repository Resource:

SaveAsString

Source Notebook

Quickly save an expression to a readable file

Contributed by: Michael Sollami

ResourceFunction["SaveAsString"][expr]

saves any expression expr to a text file.

ResourceFunction["SaveAsString"][expr,dest]

saves any expression expr to a text file at the local path dest.

Details and Options

ResourceFunction["SaveAsString"] formats files nicely when expr is a List or Association, or anything else that the resource function ReadableForm knows how to format.
ResourceFunction["SaveAsString"] creates a temporary file unless given an explicit file name as a second argument, which can either be a string "dest" or File["dest"]. This file will be created or overwritten.
If successful, ResourceFunction["SaveAsString"] will return the name of the new or updated file.

Examples

Basic Examples (4) 

Save any expression without typing out a file path:

In[1]:=
FilePrint@
 ResourceFunction["SaveAsString"][Table[PrimePi[n]^2, {n, 7}]]

Save an Association as a readable text file:

In[2]:=
fn = ResourceFunction["SaveAsString"][
  AssociationThread[Alphabet[], Range[26]]]
Out[2]=
In[3]:=
ToExpression@Import[fn, "String"]
Out[3]=

Save any objects (e.g. Dataset, ResourceObject, etc.) as string files with a comment added:

In[4]:=
FilePrint@
 ResourceFunction["SaveAsString"][
  ResourceObject[<|"Name" -> "LeNet Trained on MNIST Data", "UUID" -> "050b1a0a-f43a-4c28-b7e0-72607a918467", "ResourceType" -> "NeuralNet", "Version" -> "1.16.0", "Description" -> "Identify the handwritten digit in an image", "RepositoryLocation" -> URL[
     "https://www.wolframcloud.com/objects/resourcesystem/api/1.0"], "WolframLanguageVersionRequired" -> "11.1", "ContentElements" -> {"ConstructionNotebook", "ConstructionNotebookExpression", "EvaluationNet", "UninitializedEvaluationNet", "EvaluationExample"}|>, ResourceSystemBase -> "https://www.wolframcloud.com/objects/resourcesystem/api/1.0"], "Comment" -> "My favorite resource object."]

Save any expression to a named file and then import it:

In[5]:=
ResourceFunction["SaveAsString"][
 Table[RandomImage[1, {10, 12}, ColorSpace -> "RGB"], 5], "~/Downloads/test.txt"]
Out[5]=
In[6]:=
ToExpression@Import[%, "String"]
Out[6]=

Options (1) 

Save an expression to a named file with a comment at the top of the file:

In[7]:=
fn = ResourceFunction["SaveAsString"][{1, 2, 3}, "~/Downloads/test.txt", "Comment" -> "This is a note"]
FilePrint@fn
Out[7]=

Publisher

Michael Sollami

Version History

  • 1.0.0 – 25 February 2020

Related Resources

License Information