How should I write a Windows path in a Python string literal?

Suppose I need to refer to the path C:meshesas. If I try writing that directly, like "C:meshesas", I encounter problems – either some exception, or the path just doesn’t work. Is this because is acting as an escape character? How should I write the paths?

0

You can use always:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>'C:/mydir'
</code>
<code>'C:/mydir' </code>
'C:/mydir'

This works both in Linux and Windows.

Another possibility is:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>'C:\mydir'
</code>
<code>'C:\mydir' </code>
'C:\mydir'

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>r'C:mydir'
</code>
<code>r'C:mydir' </code>
r'C:mydir'

However, the best practice is to use the os.path module functions that always joins with the correct path separator (os.path.sep) for your OS:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>os.path.join(mydir, myfile)
</code>
<code>os.path.join(mydir, myfile) </code>
os.path.join(mydir, myfile)

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>pathlib.Path(mydir, myfile)
</code>
<code>pathlib.Path(mydir, myfile) </code>
pathlib.Path(mydir, myfile)

or:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>pathlib.Path(mydir) / myfile
</code>
<code>pathlib.Path(mydir) / myfile </code>
pathlib.Path(mydir) / myfile

9

Use the os.path module.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>os.path.join( "C:", "meshes", "as" )
</code>
<code>os.path.join( "C:", "meshes", "as" ) </code>
os.path.join( "C:", "meshes", "as" )

Or use raw strings

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>r"C:meshesas"
</code>
<code>r"C:meshesas" </code>
r"C:meshesas"

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"C:\meshes\as.jpg"
</code>
<code>"C:\meshes\as.jpg" </code>
"C:\meshes\as.jpg"

5

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> 'a'
'x07'
>>> len('a')
1
>>> 'C:meshesas'
'C:\meshesx07s'
>>> print('C:meshesas')
C:meshess
</code>
<code>>>> 'a' 'x07' >>> len('a') 1 >>> 'C:meshesas' 'C:\meshesx07s' >>> print('C:meshesas') C:meshess </code>
>>> 'a'
'x07'
>>> len('a')
1
>>> 'C:meshesas'
'C:\meshesx07s'
>>> print('C:meshesas')
C:meshess

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> list('C:test')
['C', ':', 't', 'e', 's', 't']
>>> list('C:nest')
['C', ':', 'n', 'e', 's', 't']
>>> list('C:rest')
['C', ':', 'r', 'e', 's', 't']
</code>
<code>>>> list('C:test') ['C', ':', 't', 'e', 's', 't'] >>> list('C:nest') ['C', ':', 'n', 'e', 's', 't'] >>> list('C:rest') ['C', ':', 'r', 'e', 's', 't'] </code>
>>> 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 Python’s 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:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>>>> r'C:meshesas'
    'C:\meshes\as'
    >>> print(r'C:meshesas')
    C:meshesas
    </code>
    <code>>>> r'C:meshesas' 'C:\meshes\as' >>> print(r'C:meshesas') C:meshesas </code>
    >>> r'C:meshesas'
    'C:\meshes\as'
    >>> print(r'C:meshesas')
    C:meshesas
    
  2. Python on Windows should handle forward slashes, too.

  3. You could use os.path.join

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>>>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\meshes\as'
    </code>
    <code>>>> import os >>> os.path.join('C:', os.sep, 'meshes', 'as') 'C:\meshes\as' </code>
    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\meshes\as'
    
  4. … or the newer pathlib module

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>>>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    </code>
    <code>>>> from pathlib import Path >>> Path('C:', '/', 'meshes', 'as') WindowsPath('C:/meshes/as') </code>
    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    

1

Use Path:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
print(file_to_open.read_text())
</code>
<code>from pathlib import Path data_folder = Path("source_data/text_files/") file_to_open = data_folder / "raw_data.txt" print(file_to_open.read_text()) </code>
from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
print(file_to_open.read_text())

Path takes a path-like string and adjusts everything for the current OS, either Windows or Linux. For example, on Linux it would convert all backslashes to forward slashes, and on Windows it would do the reverse.

Full article: Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux


My experience:

  • I spent 6 months using os.path.join(...), then switched to normpath(...) then finally switched to Path(...). Having used all three, Path is the best of all worlds.

Advantages of Path over os.path.join(...):

  • Cleaner.
  • Less typing.
  • Easier to read the paths (i.e. more readable).
  • Can join two different paths using / (see above).
  • More modern.

Advantages of Path over normpath(...):

  • Can join paths using / rather than having to fall back to os.path.join(...), with nested normpath calls to fix things up.
  • Cleaner.
  • Less typing.
  • Easier to read the paths (i.e. more readable).
  • Less chance of bugs when porting between Linux and Windows.
  • More modern.

Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string treats backslash () as a literal character. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.

Doing Manually Such as:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>WindowsPath("C:meshesas")
</code>
<code>WindowsPath("C:meshesas") </code>
WindowsPath("C:meshesas")

or by using r or R:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>WindowsPath(r'C:/meshes/as')
</code>
<code>WindowsPath(r'C:/meshes/as') </code>
WindowsPath(r'C:/meshes/as')

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật