The cause of the error is that the string ends in or the string is missing quotation marks
This error occurs when writing code to splice windows path. Only by looking up the data can we know that the string in Python cannot end with \
My code is as follows
import os
dirname = "test"
path = r'C:\Users\panda\Desktop\newfile\' + dirname
When running, an error will be reported
File "test.py", line 3
path = r'C:\Users\panda\Desktop\newfile\' + dirname
^
SyntaxError: EOL while scanning string literal
So how to solve it
Method 1: use os.path.join
path = os.path.join(r'C:\Users\panda\Desktop\newfile', dirname)
Method 2: the backslash of the path uses escape instead of R
path = 'C:\\Users\\panda\\Desktop\\newfile\\' + dirname
Method 3: format string
dirname="test"
path = r'C:\Users\panda\Desktop\newfile\%s' % (dirname) # The first formatting method
#从 python 2.6 start
path = r'C:\Users\panda\Desktop\newfile\{}'.format(dirname) # The second formatting method
Method 4: String interpolation
Support string interpolation from Python 3.6
# python 3.6 support string interpolation
dirname = "test"
path3 = rf'C:\Users\panda\Desktop\newfile\{dirname}'
Reference: https://docs.python.org/3/whatsnew/3.6.html#whatsnew36 -pep498
Why can’t a string end with a (backslash)
Because backslashes have other uses. In Python, when a complete string is too long, a line cannot be written and you want to wrap it. However, if you want to keep it as a string, you can wrap it with a backslash. Therefore, the backslash cannot be immediately followed by the quotation mark at the end of the string
The following is a demonstration with repl
Similar Posts:
- pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it’s not in you…
- Python Files Error: SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: tr
- Python Open File SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in …
- Python: How to Solve raise JSONDecodeError(“Expecting value”, s, err.value) from None json.decoder…
- This application failed to start because not Qt platform plugin could be initialized.
- [Solved] PyCharm Start Error: TypeError: unsupported operand type(s) for /: ‘str’ and ‘str’
- Error reporting of Python STR type dictionary conversion
- [Solved] RuntimeError: Model class apps.users.models.UserProfile doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS.
- Formatter-maven-plugin formatter validate Error
- Python pandas.read_ Oserror: initializing from file failed