I see two issues:
\t
is a tab character, \U
is the start of a 8-hex-digit Unicode character escape.
- You'd need to encode to the platform filesystem encoding,
sys.getfilesystemencoding()
, which on Windows is usually UTF-16 (little endian) or MBCS (Multi-byte character set, really meaning *any of our supported multi-byte encodings, including UTF-16), but not UTF-8. Or just pass in a Unicode string and let Python worry about this for you.
On Python 2, the following should work:
path = ur"C:\Users\Jøen\test.db"
This uses a raw unicode string literal, meaning that it'll a) not interpret \t
as a tab but as two separate characters and b) produce a Unicode string for Python then to encode to the correct filesystem encoding.
Alternatively, on Windows forward slashes are also acceptable as separators, or you could double the backslashes to properly escape them:
path = u"C:/Users/Jøen/test.db"
path = u"C:\\Users\\Jøen\\test.db"
On Python 3, just drop the u
and still not encode:
path = r"C:\Users\Jøen\test.db"
Building a path from the home directory, use Unicode strings everywhere and use os.path.join()
to build your path. Unfortunately, os.path.expanduser()
is not Unicode-aware on Python 2 (see bug 28171), so using it requires decoding using sys.getfilesystemencoding()
but this can actually fail (see Problems with umlauts in python appdata environvent variable as to why). You could of course try anyway:
path = os.path.expanduser("~").decode(sys.getfilesystemencoding())
sqlite3.connect(os.path.join(path, u"test.db"))
But instead relying on retrieving the Unicode value of the environment variables would ensure you got an uncorrupted value instead; building on Problems with umlauts in python appdata environvent variable, that could look like:
import ctypes
import os
def getEnvironmentVariable(name):
name= unicode(name) # make sure string argument is unicode
n= ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0)
if n==0:
return None
buf= ctypes.create_unicode_buffer(u'\0'*n)
ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n)
return buf.value
if 'HOME' in os.environ:
userhome = getEnvironmentVariable('HOME')
elif 'USERPROFILE' in os.environ:
userhome = getEnvironmentVariable('USERPROFILE')
sqlite3.connect(os.path.join(userhome, u"test.db"))