如何使用python选择.csv文件中的每第5行

时间:2016-02-09 15:35:31

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

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

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

谢谢你!

3 个答案:

答案 0 :(得分:0)

这将一次读取一行文件,只写行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

答案 1 :(得分:0)

这将采用任何文本文件,然后输出第一行和第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)

答案 2 :(得分:0)

如果你想使用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])