读取含空行分隔的CSV文件并按空行分组数值数据
解决方案
可以通过以下Python代码实现需求:
final_list = [] current_group = [] # 读取目标csv文件 with open('your_file.csv', 'r') as f: for line in f: stripped_line = line.strip() if stripped_line: # 非空行转为整数,加入当前分组 current_group.append(int(stripped_line)) else: # 遇到空行时,若当前分组有内容则存入结果,再重置分组 if current_group: final_list.append(current_group) current_group = [] # 处理文件末尾未被存入的最后一组数据 if current_group: final_list.append(current_group) print(final_list)
代码说明
- 用
with语句读取文件,无需手动关闭文件,避免资源泄漏 - 逐行读取时先去除行首尾空白字符,准确判断空行
- 非空行转换为整数后加入当前分组,保证数据格式正确
- 空行触发分组存入操作,同时跳过连续空行导致的空分组
- 文件读取结束后检查剩余分组,避免遗漏最后一组数据
内容的提问来源于stack exchange,提问作者CodeMaster
相关产品推荐
相关产品推荐

