天天看點

python調用csv檔案作為變量_Python CSV檔案處理/讀寫

Python CSV檔案處理/讀寫

CSV全稱為“Comma Separated Values”,是一種格式化的檔案,由行和列組成,分隔符可以根據需要來變化。 如下面為一csv檔案:

Title,Release Date,Director

And Now For Something Completely Different,1971,Ian MacNaughton

Monty Python And The Holy Grail,1975,Terry Gilliam and Terry Jones

Monty Python's Life Of Brian,1979,Terry Jones

Monty Python Live At The Hollywood Bowl,1982,Terry Hughes

Monty Python's The Meaning Of Life,1983,Terry Jones

一、列印發行日期及标題。當作檔案讀出來逐行處理:

for line in open("samples/sample.csv"):

title, year, director = line.split(",")

print(year, title)

二、使用csv子產品處理(列印發行日期及标題):

import csv

reader = csv.reader(open("samples/sample.csv"))

for title, year, director in reader:

print(year, title)

2.1、改變分隔符,建立一csv.excel的子類,并修改分隔符為”;”

# File: csv-example-2.py

import csv

class SKV(csv.excel):

# like excel, but uses semicolons

delimiter = ";"

csv.register_dialect("SKV", SKV)

reader = csv.reader(open("samples/sample.skv"), "SKV")

for title, year, director in reader:

print(year, title)

2.2如果僅僅僅是改變一兩個參數,則可以直接在reader參數中設定,如下:

# File: csv-example-3.py

import csv

reader = csv.reader(open("samples/sample.skv"), delimiter=";")

for title, year, director in reader:

print(year, title)

三、将資料存為CSV格式,通過csv.writer來生成一csv檔案。

# File: csv-example-4.py

import csv

import sys

data = [

("And Now For Something Completely Different", 1971, "Ian MacNaughton"),

("Monty Python And The Holy Grail", 1975, "Terry Gilliam, Terry Jones"),

("Monty Python's Life Of Brian", 1979, "Terry Jones"),

("Monty Python Live At The Hollywood Bowl", 1982, "Terry Hughes"),

("中國 Python's The Meaning Of Life", 1983, "Terry Jones")]

writer = csv.writer(sys.stdout)

for item in data:

writer.writerow(item)

//中文編碼問題

//writer.writerow([unicode(s).encode("utf-8") for s in item])