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

使用os.mkdir创建目录时遭遇TypeError错误求助

问题分析与解决

错误原因

os.mkdir() 的第二个参数是权限模式(必须为整数),你传入了字符串 "hi",Python无法将字符串解析为整数,因此抛出 TypeError。你混淆了参数作用:该方法的第一个参数是要创建的完整目录路径,而非父目录路径;第二个参数是可选的权限设置,不是子目录名。

正确写法

需要将父目录和子目录名拼接成完整路径后,再传给创建目录的方法:

方法1:使用 os.mkdir(需确保父目录已存在)

import os
directory = r"C:\Python"
title = "hi"
# 用os.path.join拼接完整路径,自动适配系统路径分隔符
full_dir_path = os.path.join(directory, title)
os.mkdir(full_dir_path)

方法2:使用 os.makedirs(递归创建父目录,适合父目录可能不存在的情况)

如果 C:\Python 父目录也不存在,可通过 os.makedirs 递归创建所有层级目录,加上 exist_ok=True 还能避免目录已存在时的报错:

import os
directory = r"C:\Python"
title = "hi"
full_dir_path = os.path.join(directory, title)
os.makedirs(full_dir_path, exist_ok=True)

内容的提问来源于stack exchange,提问作者Isaac Luft

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:12:02