Windows 路径中包含空格的 Python `os`
发布: (2025年12月23日 GMT+8 00:20)
1 min read
原文: Dev.to
Source: Dev.to
处理文件路径中的空格
当文件路径包含空格时,需要确保 Python 正确解释该字符串。你可以:
- 使用原始字符串(
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.")