import csv withopen('python.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1
输出:
Column names are name, department, birthday month Parker works in the Accounting department, and was born in November. Smith works in the IT department, and was born in October. Processed 3 lines.
import csv withopen('python.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'The Column names are as follows {", ".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.')
输出:
The Column names are as follows name, department, birthday month Parker works in the Accounting department, and was born in November. Smith works in the IT department, and was born in October. Processed 3 lines.
Name,Hire Date,Salary,Leaves Remaining John Idle,08/15/14,50000.00,10 Smith Gilliam,04/07/15,65000.00,8 Parker Chapman,02/21/14,45000.00,10 Jones Palin,10/14/13,70000.00,3 Terry Gilliam,07/22/14,48000.00,7 Michael Palin,06/28/13,66000.00,8
Name Hire Date Salary Leaves Remaining 0 John Idle 03/15/1450000.010 1 Smith Gilliam 06/01/1565000.08 2 Parker Chapman 05/12/1445000.010 3 Jones Palin 11/01/1370000.03 4 Terry Gilliam 08/12/1448000.07 5 Michael Palin 05/23/1366000.08