【问题标题】:Skipping more than one row in Python csv在 Python csv 中跳过多行
【发布时间】:2015-08-08 14:22:30
【问题描述】:

我正在连接到 API 以获取一些数据。输出是一个包含多行标题和传统单行标题的报表。

例子:

1. Document Name: Test
2. Document Date: 8/7/2015
3. Document ID: 3804804
4. Document Author: Joe Blow
5.
6. Date, ID, Name, Age, Sex, Result
7. 8/7/2015, 2808380, Sara Jenkings, 33, F, 208.20

在示例中,我想跳过第 1 - 5 行,将第 6 行的行写为标题行,之后的所有其他行写为普通行。

现在,我知道如何使用next(reader, None) 跳过一行,但是如果我知道要跳过的行数将始终如示例中的 5 行,我该如何跳过多行?

我通常会使用数据库来跳过行,但我想看看是否可以让 Python 正确保存数据而无需数据库做更多工作。

【问题讨论】:

    标签: python csv


    【解决方案1】:

    您可以使用itertools.islice,将要开始写入的行作为第二个参数传递,因此如果第 6 行基于 0,您可以使用 5如果 stop 为 None,则迭代将继续,直到迭代器筋疲力尽了

    import  csv
    
    from itertools import islice
    
    with open("in.csv") as f, open("out.csv","w") as out:
        r = csv.reader(islice(f, start=5,stop=None))
        wr = csv.writer(out)
        wr.writerows(r)
    

    如果您保持原样,则不一定需要 csv 模块:

    with open("in.csv") as f, open("out.csv","w") as out:
        r = islice(f, 5 ,None)
        out.writelines(r)
    

    【讨论】:

    • 谢谢。我必须将输出保存到 csv 文件,然后创建另一个文件以将 islice 输出输入为清理后的 csv 文件。它在没有 csv 模块的情况下完美运行,因为流中的数据已经是 csv 格式。但是,有没有办法将 islice 与流数据一起使用,还是我总是必须将数据输出到 csv(in.csv)并通过 islice 运行该文件?
    • 数据从何而来?
    • 数据来自 API(我相信通过 Python 的 HTTP 请求)。
    • 您也可以写入临时文件并将其切片,而不是写入磁盘或 StringIO 对象
    • 推荐使用临时文件还是内存?
    【解决方案2】:

    您可以在 for 循环中添加计数器和 if 语句。

    count = 0
    for line in opened_file:
        if count < 5:
            count += 1
            continue
        #Parse lines
    

    【讨论】:

      【解决方案3】:

      使用列表理解跳过 5 个标题行:

      import csv
      
      nheaderlines = 5
      
      with open(path + file) as csvfile:
          reader = csv.DictReader(csvfile)
      
          [next(reader, None) for item in range(nheaderlines)]
      
          for row in reader:
              print(row)
      

      【讨论】:

        猜你喜欢
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多