1

This is my code:

if mode not "w" or mode not "r+":
    # do stuff

This results in the following error:

SyntaxError: invalid syntax

Does anyone know what I'm doing wrong?

0

3 Answers 3

5

not is not a comparison operator; it is a unary boolean operator, which means it only takes one argument.

Perhaps you wanted !=, not equals?

if mode != "w" and mode != "r+":

I also replaced or with and, because if the mode is equal to 'w' it'll also not be equal to 'r+'. All those negatives make it hard enough to grok, you could use:

if not (mode == 'w' or mode == 'r+'):

if that's easier to understand, logically speaking.

You can also combine the test into one by using a tuple and a negative membership test, not in:

if mode not in ('w', 'r+'):

which is a lot easier to read and understand.

Sign up to request clarification or add additional context in comments.

1 Comment

It will, see my answer.
2

You can't compare items with this syntax:

a not b

You need to compare them with this syntax:

a != b

So rewrite your if-statement to this:

if mode != "w" or mode != "r+":
    # do stuff

Now, having said that, that is purely syntax-based changes.

The problem is, this if-statement doesn't make sense, so even if you do the above change, it will certainly not do what you want it to do.

Consider this: What if mode is "w"? Then it will not be "r+", and vice versa. In other words, every value will be different from both, or at least one of them.

I suspect you need and instead of or:

if mode != "w" and mode != "r+":
    # do stuff

Comments

2

Try this:

if not mode == "w" or not mode == "r+":
    ...

This should prevent you from seeing the SyntaxError. However, as these are common values for opening file objects to be writable, you could also try writing to the file and catch the IOError. Something like this,

f = open('blah', 'r')
try:
    f.write("Something amazing")
except IOError:
    # do something to read-only file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.