Reading and Writing CSV Files with Dictionaries

PHOTO EMBED

Sat Mar 20 2021 08:01:20 GMT+0000 (UTC)

Saved by @FlorianC #python

# read
with open('software.csv') as software:
	reader = csv.Dicteader(software)
	for row in reader:
    	print(("{} has {} users").format(row["name"], row["users"]))

# write
users = [ {"name": "Sol Mansi", "username": "solm", "department": "ITT infrastructure"}]
keys = ["name","username","department"]
with open("by_department.csv", "w") as by_department:
	writer = csv.DictWriter(by_department, fieldnames=keys) # requires dictionaries keys as parameter
	writer.writeheader() # create first line based on keys passed
	wirter.writerows(users)
content_copyCOPY