[英]Writing in a specific format to a txt file in Python
我正在嘗試將特定格式的theta
寫入.txt
文件。 我介紹了當前和預期的 output。
import numpy as np
theta = np.pi/3
with open('Contact angle.txt', 'w+') as f:
f.write(f"theta = {str(theta)}\n")
當前的 output 是
theta = 1.0471975511965976
預期的 output 是
theta = pi/3
為什么不這樣編碼:
theta = "pi/3"
with open('Contact angle.txt', 'w+') as f:
f.write(f"theta = {theta}\n")
NumPy 不懂符號數學,所以這行不通。 您可能應該使用的是SymPy 。
>>> import sympy
>>> theta = sympy.pi / 3
>>> theta
pi/3
如果您需要將其轉換為float
,您可以這樣做:
>>> float(theta)
1.0471975511965979
您可以將theta
寫為string
並使用 function eval
來獲取 theta 的值,如下所示:
from numpy import pi
theta = "pi/3"
with open('Contact angle.txt', 'w+') as f:
f.write(f"theta = {theta}\n")
eval(theta)
的 output 將為1.0471975511965976
這可能是最適合SymPy的工作。
如果 theta 永遠是pi/<integer>
,那么你可以做類似的事情
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")
如果 theta 始終是 pi 的一小部分,則代碼必須變得更加花哨: theta = <integer1>pi/<integer2>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.