user19862793
user19862793

Reputation: 171

Writing in a specific format to a txt file in Python

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

Upvotes: 0

Views: 62

Answers (4)

Mouad Slimane
Mouad Slimane

Reputation: 1067

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

Upvotes: 0

wjandrea
wjandrea

Reputation: 32944

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

Upvotes: 3

bfris
bfris

Reputation: 5805

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>

Upvotes: 0

Alex
Alex

Reputation: 717

Why not code it like this:

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

Upvotes: 1

Related Questions