1. 程式人生 > >Python csv模組讀取基本操作

Python csv模組讀取基本操作

csv即逗號分隔值,可用Excel開啟

1.向csv檔案中寫入資料

(1)列表方式的寫入

import csv

with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:
    writer = csv.writer(csvfile)

    # 寫入一行 
    writer.writerow(['1','2','3','4','5','5','6'])

    # 寫入多行
    writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])

 

(2)字典方式的寫入

import csv
with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:
    filename = ['first_name','last_name']
    # 寫入列標題
    writer = csv.DictWriter(csvfile,fieldnames=filename)
    writer.writeheader()
    writer.writerow({'first_name':'wl','last_name':'wtx'})
    writer.writerow({
'first_name': 'Lovely', 'last_name': 'Spam'}) writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

 

 

2.讀取csv檔案中的內容

(1)列表方式的讀取

import csv
with open(
'data.csv','r',encoding='utf-8') as csvfile: reader = csv.reader(csvfile) for row in reader: # 讀取出的內容是列表格式的
print(row,type(row),row[1])

 

(2)字典方式的讀取

import csv

with open('data.csv','r',encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        # 讀取的內容是字典格式的
        print(row['last_name'])