CSV
Reading CSV files
csv.reader(<file-object>, delimiter=':')
: input is CSV file. the parameterdelimiter
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 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