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
改變分隔符
建立一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
如果僅僅僅是改變一兩個引數,則可以直接在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"),
("monty python's the meaning of life", 1983, "terry jones")]
writer = csv.writer(sys.stdout)
for item in data:
writer.writerow(item)
python csv檔案的讀寫
csv檔案用於儲存 資料,可以用txt和excel開啟和編輯。寫入一次寫入一行,注意是使用list來裝要輸入的一行的內容。import csv import numpy as np out open data.csv w newline 防止每次輸入多空一行 writer csv.writer ou...
python CSV檔案處理
import csv 這種方式讀取到的每一條資料是乙個列表,所以需要通過下標的方式獲取具體某乙個值 with open stock.csv r encoding gbk as fp reader csv.reader fp for x in reader print x 3 這種方式讀取到的每一條資...
python csv檔案資料處理
使用pandas處理csv檔案 import pandas as pd import numpy as np from collections import counter 開啟csv檔案並且只使用第7列和第十四列 引號內為athlete events.csv的位址 根據個人情況修改 data pd...