class - cvs

最後更新: 2021-08-22

目錄

  • csv.reader
  • csv.write
  • csv.DictReader
  • csv.DictWriter

 


csv.reader

 

Read csv to python list

reader 返回一個 iterable object, 每隻 record 都是 py list

users.txt

u1      pw1     \\192.168.3.35\home1
u2      pw2     \\192.168.3.35\home2

Code

import csv

csvfile = open("myfile.txt")
reader = csv.reader(csvfile, delimiter = '\t')
for row in reader:
    print row

Output

['u1', 'pw1', '\\\\192.168.3.35\\home1']
['u2', 'pw2', '\\\\192.168.3.35\\home2']

 


csv.writer

 

Code

import csv

f = open('output.csv', 'w')

writer = csv.writer(f)

writer.writerow(['u3', 'pw3', '\\\\192.168.3.35\\home3'])
writer.writerow(['u4', 'pw4', '\\\\192.168.3.35\\home4'])

# vim: ts=4

 


csv.DictReader

 

Code

import csv

f = open("users.txt", 'r')

reader = csv.DictReader(f, delimiter = '\t',
    fieldnames=["User", "Pass", "Home"])

for row in reader:
    print row["User"]

Output

u1
u2

 

 


csv.DictWriter

 

Code

import csv

f = open('output.csv', 'w')

fieldnames = ['User', 'Pass']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'User': 'u5', 'Pass': 'pw5'})
writer.writerow({'Pass': 'pw6', 'User': 'u6'})

Output

cat output.csv

User,Pass
u5,pw5
u6,pw6