You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下Python执行os.mkdir报OSError [WinError 123]路径错误求助

Windows下Python创建目录WinError123问题解决

核心原因

看你给出的错误信息,路径末尾带了个换行符(\n):'C:\Users\username\xyz\forms\happy-slice\n',Windows系统不允许路径里包含换行、制表符这类控制字符,这就是报错的根源。

解决步骤

  1. 清理路径中的非法字符
    先对directory_path做首尾空白字符清理,去掉换行、空格这类多余字符:

    directory_path = directory_path.strip()
    if not os.path.exists(directory_path):
        os.mkdir(directory_path)
    

    检查下directory_path的来源——如果是从文本复制、用户输入或者文件读取的,很可能不小心带了换行符。

  2. 使用正确的路径写法
    给你几种靠谱的Windows路径写法,避免转义或非法字符问题:

    • 原始字符串写法(前面加r,防止反斜杠被解析成转义字符):
      path_to_outp = r"C:\Users\username\xyz\forms\happy-slice"
      
    • 用正斜杠代替反斜杠(Python会自动适配Windows系统):
      path_to_outp = "C:/Users/username/xyz/forms/happy-slice"
      
    • 推荐用pathlib模块(Python3.4+自带,跨平台更省心):
      from pathlib import Path
      dir_path = Path(r"C:\Users\username\xyz\forms\happy-slice")
      if not dir_path.exists():
          dir_path.mkdir()
      

补充说明

之前读取文本文件路径没问题,大概率是因为读文件时的路径没有带换行符,或者文件操作对某些空白字符的容忍度比创建目录更高,但Windows创建目录时会严格校验路径的合法性。

内容的提问来源于stack exchange,提问作者iOS Newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:05:06