<p>您可以使用访问行行号</p>
<pre><code>reader.line_num
</code></pre>
<p>但是似乎没有直接的方法来访问实际的线路(如<a href="http://%5Bhttps://docs.python.org/3/library/csv.html" rel="nofollow noreferrer">doc</a>)。以下是一种迭代方法,可避免在任何步骤将整个文件读入内存:</p>
<pre><code>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 ))
</code></pre>
<p>(已编辑:删除了其他解决方案,因为它们在其他ppl帖子上也可见)</p>