Home > Software design >  Writing in a specific format to a txt file in Python
Writing in a specific format to a txt file in Python

Time:09-08

I am trying to write theta in a specific format to a .txt file. I present the current and expected output.

import numpy as np

theta = np.pi/3

with open('Contact angle.txt', 'w ') as f: 
    f.write(f"theta = {str(theta)}\n")

The current output is

theta = 1.0471975511965976

The expected output is

theta = pi/3

CodePudding user response:

Why not code it like this:

theta = "pi/3"
with open('Contact angle.txt', 'w ') as f: 
    f.write(f"theta = {theta}\n")

CodePudding user response:

NumPy doesn't understand symbolic math, so that's not going to work. What you should probably use instead is SymPy.

>>> import sympy
>>> theta = sympy.pi / 3
>>> theta
pi/3

And if you need to convert it to float, you can do that:

>>> float(theta)
1.0471975511965979

CodePudding user response:

This might be a job that is best suited for SymPy.

If theta will always be pi/<integer>, then you could do something like

import numpy as np

theta = np.pi/3
divisor = int(np.pi/theta)

with open('Contact angle.txt', 'w ') as f: 
    f.write(f'theta = pi/{divisor}\n")

The code will have to get a lot more fancy if theta is always some fraction of pi: theta = <integer1>pi/<integer2>

CodePudding user response:

you can write theta as a string and use the function eval to get the value of theta like this:

from numpy import pi

theta = "pi/3"

with open('Contact angle.txt', 'w ') as f: 
    f.write(f"theta = {theta}\n")

the output of eval(theta) will be 1.0471975511965976

  • Related