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

如何使用Python移除CSV文件中的空列表行?

问题

我有一个名为result.csv的文件,内容如下:

ID,age,sex,city,province,country  
[]   
11816.0,44,female,NaN,Aichi    
[]   
11814.0,64,male,Nagoya City,Aichi    
[]   
11813.0,64,male,Nagoya City,Aichi 

需要处理成不含空列表[]的内容,输出如下:

11816.0,44,female,NaN,Aichi
11814.0,64,male,Nagoya City,Aichi
11813.0,64,male,Nagoya City,Aichi

我尝试了以下几种代码都没成功:

  • 错误代码1:
with open('result.csv', 'wt', newline='') as fout:
    csvout = csv.writer(fout)
    csvout.writerows('result.csv')
  • 错误代码2:
with open("filename.csv", "r") as f:
    for line in f:
        print(line, end="")
  • 错误代码3:
with open('result.csv') as csv_file:
    reader = csv.reader(csv_file)
    solution = [i] for row in reader]
    result = [[items for items in row if items != ''] for row in reader]
解决方案

方法1:基础文件操作(简单直接)

直接读取每行内容,过滤掉表头、空列表行和空行,写入新文件:

with open('result.csv', 'r') as infile, open('cleaned_result.csv', 'w') as outfile:
    # 跳过表头行
    next(infile)
    for line in infile:
        stripped_line = line.strip()
        # 过滤空行和[]行
        if stripped_line and stripped_line != '[]':
            outfile.write(stripped_line + '\n')

方法2:用csv模块处理(适合复杂CSV场景)

如果要严格处理CSV格式(比如字段含逗号的情况),用csv模块更可靠:

import csv

with open('result.csv', 'r') as infile, open('cleaned_result.csv', 'w', newline='') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    # 跳过表头
    next(reader)
    for row in reader:
        # 过滤[]行和空行
        if (len(row) == 1 and row[0] == '[]') or not row:
            continue
        writer.writerow(row)
错误代码分析
  • 第一种代码:csvout.writerows('result.csv')是把字符串的每个字符当作独立行写入,完全误解了writerows的用法,应该先读取原文件内容再写入。
  • 第二种代码:文件名写错成filename.csv,且只是原样打印所有行,没有过滤不需要的内容。
  • 第三种代码:存在语法错误(solution = [i] for row in reader]多了一个闭合括号),且csv reader只能遍历一次,第二次遍历for row in reader时已经到文件末尾,不会读取到内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:01:23