Python 2.7 如何使用python选择.csv文件中的每5行
只是一个普通的.csv文件 第一行的每个列都有标题 我想知道如何创建一个新的.csv文件,该文件具有相同的头(第一行),但每5行包含一个原始文件Python 2.7 如何使用python选择.csv文件中的每5行,python-2.7,csv,python-3.x,export-to-csv,read.csv,Python 2.7,Csv,Python 3.x,Export To Csv,Read.csv,只是一个普通的.csv文件 第一行的每个列都有标题 我想知道如何创建一个新的.csv文件,该文件具有相同的头(第一行),但每5行包含一个原始文件 谢谢大家! 这将一次读取一行文件,只写入第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: rea
谢谢大家! 这将一次读取一行文件,只写入第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
这将获取任何文本文件,然后输出第一行和第五行。如果未访问列,则不必将其作为.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库,一个更紧凑的版本将是
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])
仅当CSV中没有多行字段时,“如果未访问列”才为真。您可以有一个合法字段“第1行\n第2行”,该字段应该是输出中的单个字段。