pythonsaveexpressionsympy

Python - write symbolic expression (sympy) to txt file


What is the best way to write a symbolic expression to a txt file (so that I can use the symbolic expression after reading the txt file)?

Is there a sympy equivalent of numpy's savetxt() function for example?

for example:

from sympy import Symbol
a=Symbol('a')
b=Symbol('b')

y=a+3*b

How can I properly write and read y?


Solution

  • You could use the pickle library to store it to a file (as you can save most Python objects):

    import pickle
    with open("y.txt", "w") as outf:
        pickle.dump(y, outf)
    

    You would later load it with

    with open("y.txt") as inf:
        y = pickle.load(inf)