Windows path in Python

Windows path in Python

you can use always:


this works both in linux and windows.
Other posibility is


if you have problems with some names you can also try raw string literals:


however best practice is to use the os.path module functions that always select the correct configuration for your OS:

os.path.join(mydir, myfile)

From python 3.4 you can also use the pathlib module. This is equivelent to the above:

pathlib.Path(mydir, myfile)


pathlib.Path(mydir) / myfile

Use the os.path module.

os.path.join( C:, meshes, as )

Or use raw strings


I would also recommend no spaces in the path or file names. And you could use double backslashes in your strings.


Windows path in Python

Yes, in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence a, which is collapsed into one character that is ASCII Bell:

>>> a
>>> len(a)
>>> C:meshesas
>>> print(C:meshesas)

Other common escape sequences include t (tab), n (line feed), r (carriage return):

>>> list(C:test)
[C, :, t, e, s, t]
>>> list(C:nest)
[C, :, n, e, s, t]
>>> list(C:rest)
[C, :, r, e, s, t]

As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Pythons escape sequences is here.

There are a variety of ways to deal with that:

  1. Python will not process escape sequences in string literals prefixed with r or R:

    >>> rC:meshesas
    >>> print(rC:meshesas)
  2. Python on Windows should handle forward slashes, too.

  3. You could use os.path.join

    >>> import os
    >>> os.path.join(C:, os.sep, meshes, as)
  4. … or the newer pathlib module

    >>> from pathlib import Path
    >>> Path(C:, /, meshes, as)

Leave a Reply

Your email address will not be published. Required fields are marked *