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

使用Python os模块批量重命名文件时遭遇类型错误:can only concatenate str (not "int") to str

问题分析与解决

错误原因

出现can only concatenate str (not "int") to str错误,主要有两个核心诱因:

  1. serial_dir类型异常:该变量被意外赋值为整数类型,导致后续路径相关操作触发字符串与整数的拼接冲突。
  2. 未使用完整文件路径:os.listdir()仅返回文件夹内的文件名,而非完整路径。若脚本当前工作目录与serial_dir不一致,直接用文件名调用os.rename()会引发路径错误,甚至找不到目标文件。

修正后的代码

import os

# 确保serial_dir是字符串格式的有效路径
# 示例:serial_dir = "/Users/xxx/target_folder"

filenames = os.listdir(serial_dir)
for filename in filenames:
    # 拼接完整的源路径与目标路径
    src_path = os.path.join(serial_dir, filename)
    dst_filename = filename.replace('SN', 'NG')
    dst_path = os.path.join(serial_dir, dst_filename)
    # 执行重命名操作
    os.rename(src_path, dst_path)

额外验证步骤

  1. 检查serial_dir类型:执行print(type(serial_dir)),确认输出为<class 'str'>。若不是,将其转换为字符串(仅当路径原本为合法数字格式时适用):serial_dir = str(serial_dir)。
  2. 增加存在性判断(可选):避免因文件不存在报错,可在重命名前添加判断:
    if os.path.exists(src_path):
        os.rename(src_path, dst_path)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:20:24