简体   繁体   中英

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

Why not code it like this:

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

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM