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

Python 2.4中str.endswith()传元组报TypeError的解决求助

解决Python 2.4中str.endswith()传入元组报错的问题

这个问题我太熟悉了——Python 2.4的str.endswith()方法不支持传入元组作为参数,这个多后缀匹配的特性是从Python 2.5才新增的,所以你直接传tuple(ext)就触发了TypeError。

解决方案:手动遍历后缀列表判断

既然2.4不支持元组参数,我们可以自己遍历ext列表,逐个检查文件名是否匹配任意后缀:

import os

ext = ["n.log", ".shm", "rage"]
current_dir = os.getcwd()  # 提前获取当前目录,避免重复调用

for filename1 in os.listdir(current_dir):
    match_found = False
    # 遍历每个后缀,找到匹配就标记并跳出循环
    for suffix in ext:
        if filename1.endswith(suffix):
            match_found = True
            break
    if match_found:
        # 用os.path.join拼接路径,比直接加斜杠更安全(跨平台兼容)
        src = os.path.join(current_dir, filename1)
        irun_log = os.path.basename(src)
        # 这里可以加上你后续的处理逻辑,比如打印或移动文件

额外优化小提示

  • 提前调用os.getcwd()并赋值给变量,避免在循环里重复调用,能提升一点小效率
  • 用os.path.join拼接路径,能自动适配Windows/Linux的路径分隔符,比硬写+'/'更健壮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:02:32