简体   繁体   English

为什么 if 条件即使在控制变量为 False 时也会执行?

[英]Why if condition executes even when the control variable is False?

I have code that checks if a variable is an empty string or not.我有检查变量是否为空字符串的代码。 If it is, then the if statement executes.如果是,则执行if语句。 However, even when the string is not empty (data exists), it still executes the if statement.但是,即使字符串不为空(数据存在),它仍然会执行 if 语句。

Code I use (ripped off my big program so lot of unknown vars):我使用的代码(从我的大程序中提取了很多未知变量):


print(bytes(read_config.read(), encoding='utf-8').decode(encoding='utf-8') == "")
if bytes(read_config.read(), encoding='utf-8').decode(encoding='utf-8') == "":
    print("in if")
    with open(path, "w") as writeData: writeData.write(data)
    updateRead =  open(path, "r")
    read_config = updateRead
    print("wrote data")

Basically, I read a text file, and if the data is an empty string it should write the given data.基本上,我读取了一个文本文件,如果数据是一个空字符串,它应该写入给定的数据。 If the data from the file is not an empty string it should use the statement below the if statement (didn't include here).如果文件中的数据不是空字符串,则应使用if语句下方的语句(此处未包含)。

In the print statement, it prints out False Boolean. But it still goes to the if statement and uses the code there which resets the data.print语句中,它打印出 False Boolean。但它仍然转到if语句并使用那里的代码重置数据。 And yes, I used updateRead without the with statement on purpose.是的,我故意在没有with语句的情况下使用了updateRead

I tried this, and lot others, and I expected the statement followed by the if statement to be executed if the data is not empty, however, still didn't work.我试过这个,还有很多其他人,我希望如果数据不为空,则执行 if 语句后的语句,但是,仍然没有用。

A file can only be read once.一个文件只能读取一次。 When you call read_config.read() in the print call that reads the entire file.当您在读取整个文件的print调用中调用read_config.read()时。 Calling it again in the if statement will return an empty string since the file's already been read.if语句中再次调用它会返回一个空字符串,因为文件已经被读取了。

If you want to print what's been read for debugging purposes you'll need to save it in a variable so you don't call read() twice.如果您想打印已读取的内容用于调试目的,您需要将其保存在一个变量中,这样您就不会调用read()两次。

file_contents = bytes(read_config.read(), encoding='utf-8').decode(encoding='utf-8')
if file_contents == "":
    print("in if")
    with open(path, "w") as writeData: writeData.write(data)
    updateRead =  open(path, "r")
    read_config = updateRead
    print("wrote data")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM