Windows paths with spaces in Python's `os`

Published: (December 22, 2025 at 11:20 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

Dealing with spaces in file paths

When a file path contains spaces, you need to ensure the string is interpreted correctly by Python. You can either:

  • Use a raw string (r"...") to avoid escaping backslashes.
  • Escape each backslash (\\) manually.

Using a raw string

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.")

Using escaped 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.")
Back to Blog

Related posts

Read more »

Jupyter Notebook start

What is Jupyter Notebook? Interactive coding environment for Python and other languages like R, Julia via kernels. Modes in Jupyter - Command Mode – used to co...