CSV

Reading CSV files 
 
 csv.reader(<file-object>, delimiter=':') : input is CSV file. the parameter delimiter is optional 
 
 csv_file.txt 
 Sabrina Green,802-867-5309,System Administrator
Eli Jones,684-3481127,IT specialist
Melody Daniels,846-687-7436,Programmer
Charlie Rivera,698-746-3357,Web Developer 
 import csv

f = open("csv_file.txt")

csv_f = csv.reader(f)

for row in csv_f:

name, phone, role = row

print("Name: {}, Phone: {}, Role: {}".format(name, phone, role))
f.close() 
 Output: 
 Name: Sabrina Green, Phone: 802-867-5309, Role: System Administrator
Name: Eli Jones, Phone: 684-3481127, Role: IT specialist
Name: Melody Daniels, Phone: 846-687-7436, Role: Programmer
Name: Charlie Rivera, Phone: 698-746-3357, Role: Web Developer 
 Generating CSV 
 
 csv.writer() : input is a list with sublist, for example [[col1, col2, col3], [col1, col2, col3]]   
 .writerow() : 一次寫一筆 
 .writerows() : 一次寫多筆 
 
 import csv

hosts = [["workstation.local", "192.168.25.46"],["webserver.cloud", "10.2.5.6"]]
with open('hosts.csv', 'w') as hosts_csv:
 writer = csv.writer(hosts_csv)
 writer.writerows(hosts) 
 With list 
 Reading a CSV with the list 
 user_emails.csv 
 Full Name, Email Address
Blossom Gill, blossom@xyz.edu
Hayes Delgado, nonummy@utnisia.com
Petra Jones, ac@xyz.edu
Oleg Noel, noel@liberomauris.ca
Ahmed Miller, ahmed.miller@nequenonquam.co.uk
Macaulay Douglas, mdouglas@xyz.edu
Aurora Grant, enim.non@xyz.edu 
 
 list(csv.reader(file)) : 用 list() 函式將 CSV 內容轉成 List 格式，不使用函式也行，預設格式就是 List 
 user_data_list[1:] : 不包含第一行標題的所有內容 
 data[1].strip() : CSV 第 2 欄資料且移除前後空白字元 
 
 user_email_list = []

with open(csv_file_location, 'r') as f:

user_data_list = list(csv.reader(f))

user_email_list = [data[1].strip() for data in user_data_list[1:]] 
 
 With dictionary 
 Reading a CSV with the dictionary 
 
 csv.DictReader() : input is a CSV file, 預設第一行為標題行 
 
 # software.csv
# name,version,status,users
# MailTree,5.34,production,324
# CalDoor,1.25.1,beta,22
# Chatty Chicken,0.34,alpha,4

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

# Output:
# MailTree has 324 users
# CalDoor has 22 users
# Chatty Chicken has 4 users 
 Writing a CSV with the dictionary 
 
 csv.DictWriter(<file-object>, fieldnames=<column-list>) : input is a dictionary 
 .writerheader() : 寫標題行 
 .writerows() : input is a list with multiple dictionaries 
 
 users = [ {"name": "Sol Mansi", "username": "solm", "department": "IT infrastructure"}, 
 {"name": "Lio Nelson", "username": "lion", "department": "User Experience Research"}, 
 {"name": "Charlie Grey", "username": "greyc", "department": "Development"}]
keys = ["name", "username", "department"]
with open('by_department.csv', 'w') as by_department:
 writer = csv.DictWriter(by_department, fieldnames=keys)
 writer.writeheader()
 writer.writerows(users)

# by_department.csv:
# Name,username,department
# Sol Mansi,solm, IT infrastructure
# Lio Nelson,lion,User Experience Researcher
# Charlie Grey,greyc,Development