如何使用python选择CSV文件中的第N行 [英] How to select every Nth row in CSV file using python
问题描述
我有一个包含数百行的CSV文件,我想选择每3行并将其导出到一个新的CSV文件中,并将新的输出CSV文件命名为所选内容的第一行.
I have a CSV file with hundreds of rows, and I would like to select and export every 3 rows to a new CSV file with the new output CSV file being named after the first row of the selection.
例如在以下CSV文件中....
For example in the following CSV file....
1980 10 12
1 2 3 4 5 6 7
4 6 8 1 0 8 6
1981 10 12
2 4 9 7 5 4 1
8 9 3 8 3 7 3
我想选择前3行,并根据第一行导出到名为"1980 10 12"的新CSV,然后选择后3行,并根据以下内容导出到名为"1981 10 12"的新CSV接下来的3行中的第一行.我想使用python做到这一点.
I would like to select the first 3 rows and export to a new CSV named "1980 10 12" based on the first row then select the next 3 rows and export to a new CSV named "1981 10 12" based on the first row of the next 3 rows. I would like to do this using python.
推荐答案
使用 csv
模块,以及 itertools.islice()
每次选择3行:
Using the csv
module, plus itertools.islice()
to select 3 rows each time:
import csv
import os.path
from itertools import islice
with open(inputfilename, 'rb') as infh:
reader = csv.reader(infh)
for row in reader:
filename = row[0].replace(' ', '_') + '.csv')
filename = os.path.join(directory, filename)
with open(filename, 'wb') as outfh:
writer = csv.writer(outfh)
writer.writerow(row)
writer.writerows(islice(reader, 2))
writer.writerows(islice(reader,2))
行从读取器中获取接下来的两行,并在写入当前行(带有日期)后将它们复制到写入器CSV中首先到输出文件.
The writer.writerows(islice(reader, 2))
line takes the next 2 rows from the reader, copying them across to the writer CSV, after writing the current row (with the date) to the output file first.
您可能需要调整 csv.reader()
和 csv.writer()
对象的定界符
参数;默认值为逗号,但是您没有指定确切的格式,也许您需要将其设置为'\ t'
标签.
You may need to adjust the delimiter
argument for the csv.reader()
and csv.writer()
objects; the default is a comma, but you didn't specify the exact format and perhaps you need to set it to a '\t'
tab instead.
如果使用的是Python 3,请使用'r'
和'w'
文本模式打开文件,并设置 newline =''
两者皆有; open(inputfilename,'r',newline ='')
和 open(filename,'w',newline ='')
.
If you are using Python 3, open the files with 'r'
and 'w'
text mode, and set newline=''
for both; open(inputfilename, 'r', newline='')
and open(filename, 'w', newline='')
.
这篇关于如何使用python选择CSV文件中的第N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!