我有一个包含几个变量的文件,看起来像这样:
BTC = 375.23
SOL = 200.42
LTC = 208.91
DOT = 60.12
和一个主脚本。如何添加这些值?例如:将BTC = 375.23
修改为BTC = 420.32
。我使用的方法是:
from varfile import * # imported this way for trial and error
from varfile import BTC # imported this way for trial and error
import varfile
def blah():
varfile.BTC.append(float(420.32))
blah()
但是我得到一个错误:AttributeError: 'float' object has no attribute 'append'
我觉得我只需要将float
转换为str
,但没有运气。我发现了一些类似的帖子,但没有什么是完全相同的,没有什么是我想要的方式。
让我澄清一点,也许添加一些背景。有2个文件,一个是我的主脚本,另一个文件包含数据-我提到的变量是在varfile.py
。数据文件不需要是任何特定类型的文件,它可以是txt
文件或json
文件,任何文件。当运行主脚本时,我希望它读取变量BTC
、SOL
等的值。在读取这些值并在函数中使用之后,我想在下次运行主脚本时更改这些值。
你得到错误的原因是因为varfile.BTC
是一个浮点数。
import varfile
def blah():
# varfile.BTC = 345.23 which is a float and has no append method
varfile.BTC.append(float(420.32))
blah()
如果你的目标只是在运行时改变变量的值,这就足够了。
varfile.BTC = 0.1 # or some other value
如果您的目标是更改文件的实际内容,那么它不应该保存在.py
文件中,也不应该导入到脚本中。
如果你想改变一个纯文本文件的值,它看起来像这样:
BTC = 10 # this is the value you want to change it to
varfile = 'varfile.txt'
with open(varfile, 'rt') as txtfile:
contents = txtfile.read().split('n')
# contents.append("BTC = " + str(BTC)) # this line is if you just wanted to add a value to the end of the file.
for i,line in enumerate(contents):
if 'BTC' in line:
contents[i] = 'BTC = ' + str(BTC)
break
with open(varfile, "wt") as wfile:
wfile.write('n'.join(contents))