“EOL while scanning single-quoted string”? (backslash in string)

前端 未结 5 1690
心在旅途
心在旅途 2020-12-06 08:05
import os
xp1 = \"\\Documents and Settings\\\"
xp2 = os.getenv(\"USERNAME\")
print xp1+xp2

Gives me error

 File \"1.py\", line 2 
x         


        
5条回答
  •  星月不相逢
    2020-12-06 08:36

    You can use the os.path.expanduser function to get the path to a users home-directory. It doesn't even have to be an existing user.

    >>> 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" is expanded to the path to user's home directory. Just a single "~" gets expanded to the current users home directory.

提交回复
热议问题