I have code that checks if a variable is an empty string or not.
If it is, then the if
statement executes. However, even when the string is not empty (data exists), it still executes the if statement.
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).
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. And yes, I used updateRead
without the with
statement on purpose.
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.
CodePudding user response:
A file can only be read once. When you call read_config.read()
in the print
call that reads the entire file. Calling it again in the if
statement will return an empty string since the file's already been read.
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.
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")