Python의 `os`에서 공백이 포함된 Windows 경로
발행: (2025년 12월 23일 오전 01:20 GMT+9)
1 min read
원문: Dev.to
Source: Dev.to
파일 경로에 공백이 포함된 경우 처리하기
파일 경로에 공백이 들어있다면, 파이썬이 문자열을 올바르게 해석하도록 해야 합니다. 다음 두 가지 방법 중 하나를 사용할 수 있습니다:
- 원시 문자열(
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.")
백슬래시 이스케이프 사용하기
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.")