Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Line code return Syntax Error with open file

Tags:

python

syntax

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]")
like image 602
chenoi Avatar asked Mar 26 '26 23:03

chenoi


1 Answers

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).

like image 51
Ralf Avatar answered Mar 28 '26 14:03

Ralf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!