簡體   English   中英

為什么 if 條件即使在控制變量為 False 時也會執行?

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

我有檢查變量是否為空字符串的代碼。 如果是,則執行if語句。 但是,即使字符串不為空(數據存在),它仍然會執行 if 語句。

我使用的代碼(從我的大程序中提取了很多未知變量):


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

基本上,我讀取了一個文本文件,如果數據是一個空字符串,它應該寫入給定的數據。 如果文件中的數據不是空字符串,則應使用if語句下方的語句(此處未包含)。

print語句中,它打印出 False Boolean。但它仍然轉到if語句並使用那里的代碼重置數據。 是的,我故意在沒有with語句的情況下使用了updateRead

我試過這個,還有很多其他人,我希望如果數據不為空,則執行 if 語句后的語句,但是,仍然沒有用。

一個文件只能讀取一次。 當您在讀取整個文件的print調用中調用read_config.read()時。 if語句中再次調用它會返回一個空字符串,因為文件已經被讀取了。

如果您想打印已讀取的內容用於調試目的,您需要將其保存在一個變量中,這樣您就不會調用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