Last active
December 16, 2021 03:20
-
-
Save killertilapia/5a77bab118023023245026f74db69591 to your computer and use it in GitHub Desktop.
Reading and Writing CSV Files in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Assuming our CSV file (employee_birthday.csv) has the contents of | |
name,department,birthday month | |
John Smith,Accounting,November | |
Erica Meyers,IT,March | |
""" | |
# Reading CSV Files with csv | |
import csv | |
with open('employee_birthday.txt') 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 | |
else: | |
print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') | |
line_count += 1 | |
print(f'Processed {line_count} lines.') | |
# Reading CSV files into a dictionar with csv | |
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.') | |
# Writing CSV Files with csv | |
import csv | |
with open('employee_file.csv', mode='w') as employee_file: | |
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) | |
employee_writer.writerow(['John Smith', 'Accounting', 'November']) | |
employee_writer.writerow(['Erica Meyers', 'IT', 'March']) | |
# Writing CSV File From a Dictionary with csv | |
import csv | |
with open('employee_file2.csv', mode='w') as csv_file: | |
fieldnames = ['emp_name', 'dept', 'birth_month'] | |
writer = csv.DictWriter(csv_file, fieldnames=fieldnames) | |
writer.writeheader() | |
writer.writerow({'emp_name': 'John Smith', 'dept': 'Accounting', 'birth_month': 'November'}) | |
writer.writerow({'emp_name': 'Erica Meyers', 'dept': 'IT', 'birth_month': 'March'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment