【问题标题】:Return value as bool from text file从文本文件返回值作为布尔值
【发布时间】:2018-12-19 09:30:44
【问题描述】:

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

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

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()

【问题讨论】:

  • 你能用适当的缩进更新问题吗?
  • 请用正确的缩进编辑您的问题,我们会尽力提供帮助
  • 现在会这样做
  • 这样更好吗?

标签: python python-3.x if-statement boolean


【解决方案1】:

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

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

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)

【讨论】:

  • 出于某种奇怪的原因,即使我按照您的建议运行它 if value== "True" 它总是返回 false...或跳到 else 语句
  • 在答案中添加了新的行标签,非常感谢您
【解决方案2】:

试试这个来切换:

putback=[]
with open('values', 'r') as file:
    for e in file.readlines():
        if e=='True' or e=='False':
            print(e)
            putback.append(not e)
        else:
            putback.append(e)
with open('values','w') as file1:
     file.write('\n'.join(putback))

【讨论】:

    【解决方案3】:

    发现我的错误,谢谢大家的帮助,把if语句改成

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

    因为它是一个多行文本文档,所以缺少新的行标签

    【讨论】:

      【解决方案4】:

      据我所知,您希望将 True 更改为 False,将 False 更改为 True,其余部分保持原样。

      final_output = []
      with open("values") as file:
          data = file.readlines()
      
      for line in data:
          line = eval(line.strip())
          if isinstance(line, bool):
              print("Value is {0} Changing to {1}".format(line, not line))
              final_output.append(not line)
          else:
              final_output.append(line)
      
      with open("values", 'w') as file:
          file.write("\n".join([str(line) for line in final_output]))
      

      【讨论】:

        猜你喜欢
        • 2015-04-07
        • 1970-01-01
        • 2018-01-24
        • 2018-08-22
        • 1970-01-01
        • 2012-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多