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

Python报错:'Series' object has no attribute 'isdir' 求解决方案

问题分析与解决

错误原因

  1. isdir方法使用错误:pl_dest['Folder_Name_to_create']是Pandas的Series对象,本身没有isdir方法。isdir是os.path模块下的函数,需要传入完整的文件夹路径才能判断是否存在。
  2. iterrows()遍历错误:iterrows()返回的是(索引, 行数据)的元组,你只接收了idx,后续用pl_dest.loc[idx]会导致索引匹配错误。
  3. 路径拼接缺失:没有将基础目录test与DataFrame中的文件夹名称拼接成完整路径,直接判断无法定位到目标文件夹。

修正后的代码

首先确保导入os模块,然后修正遍历和判断逻辑:

import os
import pandas as pd

test = r'O:\Stack\Over\Flow'

# 初始化status列
pl_dest['status'] = 'not exists'

for idx, row in pl_dest.iterrows():
    # 拼接完整文件夹路径
    full_folder_path = os.path.join(test, row['Folder_Name_to_create'])
    if os.path.isdir(full_folder_path):
        pl_dest.loc[idx, 'status'] = 'exists'
        print('\texact folder already exists')

更高效的矢量化实现(推荐)

如果DataFrame数据量较大,iterrows()效率较低,建议用apply函数实现矢量化操作:

import os
import pandas as pd

test = r'O:\Stack\Over\Flow'

def check_folder_exists(folder_name):
    full_path = os.path.join(test, folder_name)
    return 'exists' if os.path.isdir(full_path) else 'not exists'

pl_dest['status'] = pl_dest['Folder_Name_to_create'].apply(check_folder_exists)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:21:01