python - 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 阅读器我无法再访问它。
是否可以检索原始原始行数据?
解决方案
您可以使用
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 帖子中也可见)
推荐阅读
- c++ - `inline` 和 `template 之间的实际区别是什么
`? - python - 如何重塑保留唯一信息的数据框?
- php - 使用 jQuery、PHP 和 MySQL 自动完成输入
- node.js - 来自 mongodb 的 Api 查询 Show TypeError: null is not a function
- javascript - 多个客户端使用的 JavaScript 包的交付机制
- c# - 从 List 中查找和删除元素
> - charts - 气泡图 Vaadin:我如何在坐标 0,0 上设置轴原点
- php - 尝试使用 slug 时找不到对象,错误 404
- c# - 从sql数据库中获取特定列并将值保存在asp.net c#中的变量中
- spring-boot - Spring Boot x509 测试-pcf