I want to check if a file doesn't exist, I could simply use "not" instead of ~, but I'm curious why it works that way? Why it doesn't return -1 for example? Can anyone teach me?
"file.csv" does exist in this example
not os.path.isfile("file.csv")
Output:
False
Code 2
~os.path.isfile("file.csv")
Output:
-2
Perhaps this will make things clearer.
Let's say that your file 'file.csv' exists.
You can then assert that:
os.path.isfile("file.csv") == True
You can also assert (in Python and some other languages) that:
True == 1
In Python, tilde is the bitwise complement operator. That means that all bits in the value to which the operator is applied are inverted.
This is more easily described if you imagine that integers are constrained to a certain number of bits (which is not the case in Python but would be, for example, in C). For brevity let's say that a signed int is described in 16 bits. So, the binary representation of decimal 1 would be 0000000000000001.
Now apply the complement operator to that value and you get 1111111111111110 - i.e., all bits inverted
As the most significant bit is 1 then this is a negative number.
In fact, it's the 16-bit representation of decimal -2