"EOL while scanning a single quote string"? (backslash in a string)

import os
xp1 = "\Documents and Settings\"
xp2 = os.getenv("USERNAME")
print xp1+xp2

Gives me an error

 File "1.py", line 2 
xp1 = "\Documents and Settings\"
                               ^
SyntaxError: EOL while scannning single-quoted string

Can you help me, do you see a problem?

+3
source share
5 answers

The backslash character is interpreted as an escape. Use double backslash for window paths:

>>> xp1 = "\\Documents and Settings\\"
>>> xp1
'\\Documents and Settings\\'
>>> print xp1
\Documents and Settings\
>>> 
+20
source

Besides the problem of the black character, do not add the path by using the "+" - use os.path.join.

Also, create a path to the user's home directory, which is likely to fail in new versions of Windows. For this, pywin32 has API functions.

+11
source

os.path.expanduser, . .

>>> import os.path
>>> os.path.expanduser('~foo')
'C:\\Documents and Settings\\foo'
>>> print os.path.expanduser('~foo')
C:\Documents and Settings\foo
>>> print os.path.expanduser('~')
C:\Documents and Settings\MizardX

"~user" . "~" .

+8

Python, , escape- ( xp1 =... , ).

, python, .

, . r :

xp1 = r"\Documents and Settings\"

, os.path, "/" "\" O.S. . :

import os.path
xp1 = os.path.join("data","cities","geo.txt")

"//geo.txt" Linux "data\cities\geo.txt" Windows.

+6

\" " , . , raw r"\" .

( ):

'r' 'R', , , , . , r "\n" : "n". , ; , r "\" " , : ; r "\" ( ) In particular, a raw string cannot end with a single backslash (since a backslash avoids the next quote character). Note also that a single backslash followed by a newline character is interpreted as the two characters as part of a string, and not as a continuation of a line.

@MizardX's answer provides the correct way to code what you do, independently.

+4
source

Source: https://habr.com/ru/post/1702551/


All Articles