我有一個名為“employee_birthday.txt”的 csv 檔案:
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
以下腳本設法正確列印內容:
import csv
with open('employee_birthday.txt', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count = 1
print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
line_count = 1
print(f'Processed {line_count} lines.')
輸出如下:
Column names are name, department, birthday month
John Smith works in the Accounting department, and was born in November.
Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
實際上這是來自關于 csv的在線教程。令我困惑的是 for 回圈的第一次迭代。似乎 for 回圈的最后兩行被神奇地跳過了,并且在第一次互動期間沒有列印任何東西,即使沒有 aelse或continue高于列印(第 10 行)。這對我來說沒有意義。
uj5u.com熱心網友回復:
如果你只是print('loop')在你的回圈中添加一個簡單的,你會看到發生了什么:
import csv
with open('test.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
for row in csv_reader:
print('loop') # prints once per loop
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count = 1
print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
line_count = 1
print(f'Processed {line_count} lines.')
結果是:
loop
Column names are name, department, birthday month
John Smith works in the Accounting department, and was born in November.
loop
Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
loop只列印了 2秒。因為在 aDictReader只有資料值被回圈通過。標題行已被處理并且標題存盤在閱讀器物件中。
當您執行print(f'Column names are {", ".join(row)}')第一個資料行字典中的鍵時,將使用該行來列印該行,因為每一行都內置了標題:
{'name': 'John Smith', 'department': 'Accounting', 'birthday month': 'November'}
您會看到,Processed 3 lines因為在您的第一次迭代中,line_count增加了兩次。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520952.html
標籤:PythonCSV
