class - cvs

最後更新: 2021-08-22

 


csv.reader

 

cat users.txt

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

Code

import csv

csvfile = open("myfile.txt", 'rt')
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']

Remark

reader default 是用 comma"," 作分隔

reader - 獲得一個 iterable object, 每隻 record 都是 list

 


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.write

 

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.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