将从文件读取的 True/False 值转换为布尔值

Convert True/False value read from file to boolean(将从文件读取的 True/False 值转换为布尔值)
本文介绍了将从文件读取的 True/False 值转换为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从文件中读取 True - False 值,我需要将其转换为布尔值.目前它总是将其转换为 True,即使该值设置为 False.

I'm reading a True - False value from a file and I need to convert it to boolean. Currently it always converts it to True even if the value is set to False.

这是我正在尝试做的 MWE:

Here's a MWE of what I'm trying to do:

with open('file.dat', mode="r") as f:
    for line in f:
        reader = line.split()
        # Convert to boolean <-- Not working?
        flag = bool(reader[0])

if flag:
    print 'flag == True'
else:
    print 'flag == False'

file.dat 文件基本上由一个字符串组成,其中写入值 TrueFalse.这种安排看起来非常复杂,因为这是来自更大代码的最小示例,这就是我将参数读入其中的方式.

The file.dat file basically consists of a single string with the value True or False written inside. The arrangement looks very convoluted because this is a minimal example from a much larger code and this is how I read parameters into it.

为什么flag总是转换成True?

推荐答案

bool('True')bool('False') 总是返回 True 因为字符串 'True' 和 'False' 不为空.

bool('True') and bool('False') always return True because strings 'True' and 'False' are not empty.

引用一位伟人(和 Python 文档):

To quote a great man (and Python documentation):

可以测试任何对象的真值,用于 if 或 while条件或作为以下布尔运算的操作数.这以下值被认为是错误的:

5.1.TruthValueTesting

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • 任何数字类型的零,例如,00L0.00j.
  • 任何空序列,例如,''()[].

所有其他值都被认为是 true —所以很多类型的对象总是正确的.

All other values are considered true — so objects of many types are always true.

内置 bool函数使用标准的真值测试程序.这就是为什么你总是得到 True.

要将字符串转换为布尔值,您需要执行以下操作:

To convert a string to boolean you need to do something like this:

def str_to_bool(s):
    if s == 'True':
         return True
    elif s == 'False':
         return False
    else:
         raise ValueError # evil ValueError that doesn't tell you what the wrong value was

这篇关于将从文件读取的 True/False 值转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)