<p>看起来<a href="https://docs.python.org/3/library/csv.html#csv.reader" rel="nofollow noreferrer">^{<cd1>}</a>并没有公开它正在迭代的文件对象,但是,您可以使用<a href="https://docs.python.org/3/library/csv.html#csv.csvreader.line_num" rel="nofollow noreferrer">reader's ^{<cd2>}</a>属性来实现您想要的</p>
<p>例如:</p>
<pre class="lang-python prettyprint-override"><code>import csv
file = open("my_csv_file.csv")
lines = file.readlines()
reader = csv.reader(lines)
for row in reader:
# row is an array or dict
try:
parsed_data = my_data_parser(row)
except MyDataParserError:
print(f"ERROR in line number {reader.line_num}")
print("Full line:")
print(lines[reader.line_num])
file.close()
</code></pre>
<h2>另类</h2>
<p>如果希望避免总是将文件加载到内存中,则可以保留最初读取文件的方式,并且仅在发生错误时将整个文件读取到内存中:</p>
<pre class="lang-python prettyprint-override"><code>import csv
reader = csv.reader(open("my_csv_file.csv"))
for row in reader:
# row is an array or dict
try:
parsed_data = my_data_parser(row)
except MyDataParserError:
# Only read the whole file into memory when an error occurred.
file = open("my_csv_file.csv")
lines = file.readlines()
file.close()
print(f"ERROR in line number {reader.line_num}")
print("Full line:")
print(lines[reader.line_num])
</code></pre>