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

编写单行代码筛选特定文件时遇权限错误,求解决方案

问题解决思路与修正代码

你的代码主要存在两个核心问题:

  1. .ipynb_checkpoints是Jupyter生成的目录而非普通文件,直接用open()访问会触发权限拒绝错误
  2. 排除条件存在语法错误(filename =!是错误写法),且未优先过滤目录类对象

修正后的单行代码

import os; [f for f in os.listdir(".") if os.path.isfile(f) and len(f) > 10 and len(open(f).readlines()) > 10 and not f.endswith(".ipynb_checkpoints")]

关键改进说明

  • 新增os.path.isfile(f)判断:先筛选出当前目录下的文件,直接跳过所有目录(包括.ipynb_checkpoints),从根源避免权限问题
  • 修正语法错误:用not f.endswith(".ipynb_checkpoints")准确排除指定后缀的文件
  • 若要处理大文件,可改用生成器表达式统计行数,更节省内存:
import os; [f for f in os.listdir(".") if os.path.isfile(f) and len(f) >10 and (sum(1 for _ in open(f))>10) and not f.endswith(".ipynb_checkpoints")]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:20:33