编写单行代码筛选特定文件时遇权限错误,求解决方案
问题解决思路与修正代码
你的代码主要存在两个核心问题:
.ipynb_checkpoints是Jupyter生成的目录而非普通文件,直接用open()访问会触发权限拒绝错误- 排除条件存在语法错误(
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
相关产品推荐
相关产品推荐

