3

I run a script with the code to open a file and it returns SyntaxError. The script is an open source script that I want to test.

with open(f"/home/mine/myfoldr/myapp.yml", "r") as file:

The line above returns the following error:

File "./startup.py", line 28
    with open(f"/home/mine/myfoldr/myapp.yml", 'r') as file:
                                            ^

I just don't understand what does it mean with f" here, after open(f"...). Because normally it will be write something like below, without f.

with open("/home/mine/myfoldr/myapp.yml", "r") as file:

I think its not a typo because other line code in the script also..have the same style f, for example:

print(f"Which section do you want to change?"
      f"[Application/Controller/Database]")
2
  • Does it also throw an error if you remove the f that is before the file name? Commented Sep 6, 2019 at 14:42
  • it will thrw an error to the next line code that also hav 'f'... thanks Commented Sep 6, 2019 at 14:58

1 Answer 1

2

The f at the start of strings is called f-string, introduced with PEP 489 starting at Python 3.6.

It is used for string formatting, similar to .format(). There are a lot of tutorials on it you can read. The basic example:

x = 22
print('this is {}'.format(x))
print(f'this is {x}')

Here, both lines will output the same resulting string this is 22.


You probably get the error because you are using a version older than Python 3.6, some version where f-strings are not supported.

To test the third-party code you will have to use a newer Python version or modify the code yourself (but this last options may be a lot of work and may introduce some unintentional errors).

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

5 Comments

i tried run the file sudo python3 startup.py and it still return d same... in my env i have python3, 3.5, 3.6 ....
@chenoi can you try using python3.6 startup.py?
i tried that ..no more syntax error but now got module not found error...for example File "startup.py", line 10, in <module> import mysql.connector ModuleNotFoundError: No module named 'mysql' I tried reinstall again requirements.txt using pip3...but another modulenotfound ModuleNotFoundError: No module named 'pip._internal'
@chenoi Careful: for which Python version is pip3 installing the packages? It can be quite messy to use pip when you have more than 1 python version installed
Great Ralf.... thanks...for your support and guideline... thanks again... i will try to resolve it....at least i know...d issue is due to my python version that i need to apply 3.6 version

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.