csv 有没有办法在指定行启动DictReader?

vngu2lb8  于 2023-01-18  发布在  其他
关注(0)|答案(3)|浏览(191)

我想打开一个读取器对象并进行集成,直到匹配“Transaction Date”,在这种情况下,使用DictReader获取dict对象。

starting=0
with open(argv[1], 'r')as file:
    transaction = list(csv.reader(file))
    #what line is the dictReader on?
    counter=0
    for line in transaction:
        counter+=1
        if line[0]=='Transaction Date':
            starting=counter-1
    
    a=csv.DictReader(file)
    
    for b in a:
        print(b)
abithluo

abithluo1#

可以使用itertools.dropwhile,类似于

from itertools import dropwhile

def f(line):
    return line[0] != 'Transaction Date'

with open(argv[1], 'r') as file:
    transaction = dropwhile(f, csv.reader(file))
    for b in transaction:
        print(b)
wb1gzix0

wb1gzix02#

从DictReader开始在while循环中检查每一行,直到你的条件被满足;然后用for循环迭代以处理其余部分。

import io, csv

data = '''col_a,col_b
transaction week,4
transaction second,5
transaction date,6
foo,7
bar,8
the end,9
'''
with io.StringIO(data) as f:
    reader = csv.DictReader(f)
    row = next(reader)
    while row['col_a'] != 'transaction date':
        row = next(reader)
    for row in reader:
        print(row)
wnavrhmk

wnavrhmk3#

file = open(argv[1],'r')
# go to that line
for i in range(starting):
    file.readline()
    
# read in as dict
d = list(csv.DictReader(file))

此答案由CC BY-SA 4.0下的OP Yes No发布为问题“是否有方法在指定行启动DictReader?”的edit

相关问题