如何通过子串筛选从文件列表中提取不含FC的CSV文件
提取不含'FC'的CSV文件解决方案
问题场景
现有以下CSV文件列表:
TXSHP_20240712052921.csv TXSHP_20240715045301.csv TXSHP_FC_20210323084010.csv TXSHP_FC_20231116060918.csv
需要筛选出文件名中**不含'FC'**的文件。
原代码问题分析
你写出的代码存在两个关键问题:
- 逻辑与运算符错误:Python中逻辑与要用
and,而非位运算符& - 条件判断冗余:
'FC' in file == False可以简化为更直观的'FC' not in file
修正后的代码
方式一:保留原循环结构优化
import os def get_archive_filelist_chip(archiveFldr): nonedi_files_chip = [] for file in os.listdir(archiveFldr): if file.endswith(".csv") and 'FC' not in file: nonedi_files_chip.append(file) return nonedi_files_chip
方式二:列表推导式(更简洁写法)
import os def get_archive_filelist_chip(archiveFldr): return [file for file in os.listdir(archiveFldr) if file.endswith(".csv") and 'FC' not in file]
代码说明
- 先通过
file.endswith(".csv")过滤出CSV格式文件 - 再通过
'FC' not in file排除文件名包含'FC'的文件 - 列表推导式写法能在一行完成筛选,代码更紧凑易读
内容的提问来源于stack exchange,提问作者Ben Smith
相关产品推荐
相关产品推荐

