Windows 路径中包含空格的 Python `os`

发布: (2025年12月23日 GMT+8 00:20)
1 分钟阅读
原文: 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.")
Back to Blog

相关文章

阅读更多 »

数据架构师大师专业工作簿

概述:我构建了一个模块化、可审计的数据工程项目,并希望与社区分享。特性——干净的、生产级别的 Python——SQL pat...

Python中的随机模块

概述:Python 中的 random 模块提供了生成随机性的工具,例如随机数、从序列中选择项目以及打乱数据。它是……