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

Python中'unexpected indent'错误求助:创建新目录代码报错

解决Python路径处理中的'unexpected indent'及相关错误

1. 缩进错误的直接修复

unexpected indent错误的核心原因是代码缩进不一致,大概率是这一行混用了空格和制表符,或者缩进层级和循环内其他代码不匹配:

newFilePath.mkdir(parents=True)

检查这一行的缩进:统一使用4个空格(Python官方规范),确保它和外层for name in files:循环内的代码缩进层级完全一致,不要混合制表符与空格。

2. 核心逻辑错误:字符串无法调用mkdir方法

即使修复缩进,你仍会报错——因为newFilePath是字符串类型,而mkdir()是pathlib.Path对象的专属方法。必须先将字符串转为Path对象:

# 把字符串拼接后的路径转为Path对象
newFilePath = Path(rootDir + standaard + dag + graad + klas + uur + bestand)

3. 其他潜在问题的优化修复

(1)避免覆盖内置函数

不要用list作为变量名,它是Python内置函数,改为slash_positions这类自定义名称:

slash_positions = [pos for pos, char in enumerate(filePath) if char == '\\']

(2)路径字符串使用原始格式

Windows路径中的\会被解析为转义字符,用原始字符串避免报错:

root = r"C:\Voorleessoftware\"

(3)用Pathlib简化路径分割

手动查找分隔符的方式容易出错,pathlib.Path的parts属性可以直接获取路径各部分,更可靠:

file_path_obj = Path(filePath)
# 按你的路径结构提取各部分
rootDir = file_path_obj.parts[0]
standaard = file_path_obj.parts[1]
dag = file_path_obj.parts[2]
uur = file_path_obj.parts[3]
graad = file_path_obj.parts[4]
klas = file_path_obj.parts[5]
bestand = file_path_obj.parts[6]

(4)创建目录的正确姿势

newFilePath包含文件名,不能直接调用mkdir(),需要先获取父目录路径:

# 创建文件所在的目录,exist_ok=True避免重复创建报错
newFilePath.parent.mkdir(parents=True, exist_ok=True)

修复后的完整代码

import os
from pathlib import Path

# 使用原始字符串处理Windows路径
root = r"C:\Voorleessoftware\"
path = os.path.join(root, "targetdirectory")

for path, subdirs, files in os.walk(root):
    for name in files:
        filePath = os.path.join(path, name)
        # 转为Path对象简化路径操作
        file_path_obj = Path(filePath)
        
        # 通过parts属性直接提取路径各部分
        rootDir = file_path_obj.parts[0]
        standaard = file_path_obj.parts[1]
        dag = file_path_obj.parts[2]
        uur = file_path_obj.parts[3]
        graad = file_path_obj.parts[4]
        klas = file_path_obj.parts[5]
        bestand = file_path_obj.parts[6]
        
        # 用Path的拼接方式自动处理分隔符
        newFilePath = Path(rootDir) / standaard / dag / graad / klas / uur / bestand
        
        # 创建目标文件的父目录
        newFilePath.parent.mkdir(parents=True, exist_ok=True)

内容的提问来源于stack exchange,提问作者Joram Laureyns

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:31:02