首页 > 解决方案 > Python csv获取原始原始数据行

问题描述

在 python 中,很容易读取和解析 csv 文件并逐行处理:

reader = csv.reader(open("my_csv_file.csv"))
for row in reader:
    # row is an array or dict 
    parsed_data = my_data_parser(row)
    

其中my_data_parser是我自己的一段逻辑,它接受输入数据、解析并执行逻辑。

如果我的解析器失败,我想记录 csv 文件的整个原始行,但似乎从 csv 阅读器我无法再访问它。

是否可以检索原始原始行数据?

标签: pythoncsvreader

解决方案


您可以使用

reader.line_num

但似乎没有直接的方式来访问实际的线路(说doc)。这是避免在任何步骤将整个文件读取到内存的迭代方法:

import csv 
class MyException(Exception):
    pass

def super_logic(line): # Some silly logic to get test code running
   if len(line) != 2 or line[1] != '1':
       raise MyException("Invalid value")
   print("Process: %s" % line)

class LastLineReader:
    
    def __init__(self, fn ):
        self.fid = open(fn)
    def __iter__(self):
        return self
    def __next__(self):
        line = self.fid.readline() # Read single line and cache it local object
        if len(line) == 0:
            raise StopIteration()
        self.current_line = line.strip()
        return line
           

reader_with_lines = LastLineReader( "my_csv_file.csv" )
reader = csv.reader( reader_with_lines )
for line in reader:
   try:
     super_logic(line)
   except MyException as e:
     print("Got exception: %s at line '%s'" % ( e, reader_with_lines.current_line ))

(已编辑:删除了其他解决方案,因为它们在其他 ppl 帖子中也可见)


推荐阅读