gpt4 book ai didi

python - 从文本文件返回 bool 值

转载 作者:行者123 更新时间:2023-12-01 09:15:42 25 4
gpt4 key购买 nike

尝试编写多个脚本来访问一个文本文件,以从该文本文件中检索其切换值,然后返回 false 值并将其更改为 true,反之亦然。

值总是返回为 false,不确定我缺少什么,但这是文本文件:

1
False
3
True
5
6
7
8
9

这是源代码:

def append():
with open('values', 'r') as file:
# read a list of lines into data
data = file.readlines()
# now change the line
re_value = value

data[1] = re_value+"\n"
# and write everything back
with open('values', 'w') as file:
file.writelines(data)
print("value changed to "+re_value)

def read() -> bool:
#opens the value file to find the value of the toggle
f=open("values", "r")

for x, line in enumerate(f):
if x == 1:
toggle = line
print(toggle)
return toggle
f.close()


toggle = read()

if toggle:
print("Light is on turn it off")
#runs command to turn off the light
#runs command to change value for light
value = "False"
append()
else:
print("Light is off turn it on")
#runs command to turn on the light
#runs command to change value for light
value = "True"
append()

最佳答案

似乎您用来评估条件的 boolean 值是一个字符串。

在这种情况下,您可以将其保留为字符串:

if value == "True":
print "Condition is true!"

或者实现类似的东西:

def str2bool(v):
return v.lower() in ("true",) # you can add to the tuple other values that you consider as true if useful

print str2bool(value)

关于python - 从文本文件返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com