0

I am trying Python with VSCode and it is giving me a headache with formatting. I have te following code:

import os
filePath = "get-file-size.py"

try:
    size = os.path.getsize(filePath)

except OSError:
    print("Path '%s' does not exist or is not accesible", %filePath)
    sys.exit()

print("File size (in bytes): ", size)

VSCode gives me the following error:

invalid syntax (, line 10)

This error happens because it adds an extra space after % in the except print statement as below:

print("Path '%s' does not exist or is not accesible", % filePath)

Can someone point me in the right direction on how to solve this? I am pretty sure it is because a formatter, but how, when, which one?

Thanks in advance

1
  • The Vscode Python extension supports source code formatting using autopep8 by default but it can change if you have installed any other formatter. Commented Jul 4, 2020 at 20:17

1 Answer 1

2

Delete the comma before the percent sign:

print("Path '%s' does not exist or is not accesible" % filePath)

The percent sign is the formatting operator. It takes a string on the left and stuff to insert to the string on the right, it's not a separate argument of the print function.

Also, it's better to use str.format:

print("Path '{}' does not exist or is not accesible".format(filePath))

or if you're using python 3.6 and above, use f-strings:

print(f"Path '{filePath}' does not exist or is not accesible")

You can read more about it here.

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

3 Comments

'%s' but the quotes I think its not necessary
Thank you!!!!! str.format and/or f-strings did the job
I assumed the quotes were to surround the path in the message you print, oh well

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.