DEV Community

Cover image for Windows paths with spaces in Python's `os`
Nazanin Ashrafi
Nazanin Ashrafi

Posted on

Windows paths with spaces in Python's `os`

Dealing with spaces in file paths is an issue that I keep running into.
So here's a very short blog to save us time and headaches.

You can either use r string or double backslashes (\\).

1. The Recommended Fix: Use a Raw String r

import os

# Correct: Use 'r' before the string to create a raw string
path_with_spaces = r"F:\python\New folder (2)"

if os.path.isdir(path_with_spaces):
    print(f"'{path_with_spaces}' is a directory.")
else:
    print(f"'{path_with_spaces}' is NOT a directory or does not exist.")
Enter fullscreen mode Exit fullscreen mode

2. Alternative Fix: Double Backslashes

import os

# Alternative: Escape the backslashes
path_with_spaces_escaped = "F:\\python\\New folder (2)"

if os.path.isdir(path_with_spaces_escaped):
    print(f"'{path_with_spaces_escaped}' is a directory.")
else:
    print(f"'{path_with_spaces_escaped}' is NOT a directory or does not exist.")
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
amelia2802 profile image
Amelia Dutta

πŸ”₯πŸ”₯πŸ”₯

Collapse
 
shemith_mohanan_6361bb8a2 profile image
shemith mohanan

Nice, clear tip β€” this is one of those small Python gotchas that bites everyone at least once πŸ˜„

Raw strings are definitely the cleanest option, especially when paths get longer. Simple post, very practical for beginners πŸ‘

Collapse
 
shahrouzlogs profile image
Shahrouz Nikseresht

Short, sweet, and super helpful! Keep dropping these knowledge bombs, you're killing it dude! πŸ˜πŸš€