tags:

views:

503

answers:

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

Gives me error

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

Can you help me please, do you see the problem?

+16  A: 

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

>>> xp1 = "\\Documents and Settings\\"
>>> xp1
'\\Documents and Settings\\'
>>> print xp1
\Documents and Settings\
>>>
gimel
Thanks, @recursive - a slip of the fingers...
gimel
+10  A: 

Additionally to the blackslash problem, don't join paths with the "+" operator -- use os.path.join instead.

Also, construct the path to a user's home directory like that is likely to fail on new versions of Windows. There are API functions for that in pywin32.

Torsten Marek
+1 os.path.join is the way to go. Would os.getenv('HOME') be set on Win32? I don't have an MS box to check..
Alabaster Codify
My poor little XP-in-a-VM has the "USERPROFILE" environment variable, which points to the home directory, but I don't know how official it is.
Torsten Marek
os.path.join is really handy
kigurai
+6  A: 

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.

MizardX
+3  A: 

Python, as many other languages, uses the backslash as an escape character (the double-quotes at the end of your xp1=... line are therefore considered as part of the string, not as the delimiter of the string).

This is actually pretty basic stuff, so I strongly recommend you read the python tutorial before going any further.

You might be interested in raw strings, which do not escape backslashes. Just add r just before the string:

xp1 = r"\Documents and Settings\"

Moreover, when manipulating file paths, you should use the os.path module, which will use "/" or "\" depending on the O.S. on which the program is run. For example:

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

will produce "data/cities/geo.txt" on Linux and "data\cities\geo.txt" on Windows.

MiniQuark