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

如何解决调用os.fspath传路径列表时报TypeError: expected str...not list错误

问题解决方案

报错根因

os.fspath() 仅支持传入单个字符串、字节或类路径对象,你传入的 batch_files 是存储了多个文件路径的列表,类型不匹配触发报错。同时 shutil.move() 也无法直接对路径列表执行批量移动操作,需要遍历列表逐个处理文件。

修正后完整代码

import os
import pandas as pd
import re
import psycopg2 as ps
import shutil

sub_folder = 'team project'

current_folder = os.getcwd()
working_folder = os.path.join(current_folder, sub_folder)

files = os.listdir(working_folder)

batch_files = [f for f in files if 'April 16' in f or 'April 23' in f]
batch_files = [os.path.join(working_folder, f) for f in batch_files]

# 合并Excel数据
df_list = []
for f in batch_files:
    data = pd.read_excel(f, 'Sheet1')
    df_list.append(data)
df = pd.concat(df_list, ignore_index=True)

# 移动源文件到目标文件夹
des_folder = 'destination'
destination = os.path.join(current_folder, des_folder)
# 自动创建目标文件夹,避免路径不存在报错
os.makedirs(destination, exist_ok=True)

# 逐个遍历移动文件
for file_path in batch_files:
    shutil.move(file_path, destination)

关键改动说明

  • 替换了Pandas已废弃的DataFrame.append()方法,改用pd.concat()完成多表合并,兼容性更强,新增ignore_index=True参数重置合并后的行索引,避免索引重复
  • 移除了错误的批量路径转换逻辑,改为遍历batch_files列表逐个调用shutil.move()移动文件
  • 新增目标文件夹自动创建逻辑,os.makedirs()的exist_ok=True参数可避免目标文件夹已存在时触发报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 10:36:03