【问题标题】:how to select every 5th row in a .csv file using python如何使用python选择.csv文件中的每5行
【发布时间】:2016-02-09 15:35:30
【问题描述】:

只是一个普通的 .csv 文件 第一行的每一列都有标题。

我想知道如何创建一个新的 .csv 文件,它具有相同的标题(第一行),但包含原始文件的每 5 行?

谢谢!

【问题讨论】:

    标签: python-2.7 csv python-3.x export-to-csv read.csv


    【解决方案1】:

    这将获取任何文本文件并在此之后输出第一行和每 5 行。如果未访问列,则不必将其作为 .csv 进行操作:

    with open('a.txt') as f:
        with open('b.txt','w') as out:
            for i,line in enumerate(f):
                if i % 5 == 0:
                    out.write(line)
    

    【讨论】:

    • "如果列未被访问" 仅当 CSV 中没有多行字段时为 true。您可以有一个合法的字段“line 1\nline 2”,它应该是输出中的一个字段。
    【解决方案2】:

    这将一次读取文件一行,并且只写入第 5、10、15、20 行...

    import csv
    
    count = 0
    
    # open files and handle headers
    with open('input.csv') as infile:
        with open('ouput.csv', 'w') as outfile:
            reader = csv.DictReader(infile)
            writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames)
            writer.writeheader()
    
            # iterate through file and write only every 5th row
            for row in reader:
                count += 1
                if not count % 5:
                    writer.writerow(row)
    

    (使用 Python 2 和 3)

    如果您希望从数据行 #1 开始,将第 1、6、11、16 行...在顶部更改为:

    count = -1
    

    【讨论】:

      【解决方案3】:

      如果你想使用 csv 库,一个更紧凑的版本将是......

      import csv
      
      # open files and handle headers
      with open('input.csv') as infile:
          with open('ouput.csv', 'w') as outfile:
              reader = csv.DictReader(infile)
              writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames)
              writer.writeheader()
      
              # iterate through file and write only every 5th row
              writer.writerows([x for i,x in enumerate(reader) if i % 5 == 4])
      

      【讨论】:

        猜你喜欢
        • 2018-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-21
        • 2021-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多