簡體   English   中英

Python中以特定格式寫入txt文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM