python之csv模組學習

2021-10-06 13:15:55 字數 3181 閱讀 4364

import csv

# 讀取字串

for row in csv.reader(

['one,two,three'])

:print

(row)

# ['one', 'two', 'three']

# 寫資料

with

open

('test_csv_data.csv'

,'w'

, newline='')

as f:

writer = csv.writer(f, delimiter=

' ',quotechar=

'|', quoting=csv.quote_minimal)

writer.writerow(

['my name is'

,'tom'

,'bob'

,'jim'

,'may'])

writer.writerow(

['color is'

,'red'

,'yellow green'

,'blue'])

# 讀資料

with

open

('test_csv_data.csv'

, newline='')

as f:

spamreader = csv.reader(f, delimiter=

' ', quotechar=

'|')

for row in spamreader:

print

(', '

.join(row)

)# my name is, tom, bob, jim, may

# color is, red, yellow green, blue

# 寫入csv檔案 writer.writerow和writer.writerows

with

open

('csv_test1.csv'

,'w'

, newline='')

as f:

# 如不指定newline='',有時則每寫入一行,將有一空行被寫入

writer = csv.writer(f)

writer.writerow(

['name'

,'age'

,'tel'])

# 寫入一行用writerow

with

open

('csv_test2.csv'

,'w'

, newline='')

as f:

# 如不指定newline='',有時則每寫入一行,將有一空行被寫入

writer = csv.writer(f)

data =[(

'tom'

,'25'

,'1367890900'),

('jim'

,'18'

,'1367890800')]

writer.writerows(data)

# 多行用writerows

## 讀取csv檔案

with

open

('csv_test1.csv'

, encoding=

'utf-8'

)as f:

csv_reader = csv.reader(f)

for row in csv_reader:

print

(row)

with

open

('csv_test2.csv'

, encoding=

'utf-8'

)as f:

csv_reader = csv.reader(f)

for row in csv_reader:

print

(row)

# ['name', 'age', 'tel']

# ['tom', '25', '1367890900']

# ['jim', '18', '1367890800']

# 以字典方式寫入csv 並讀取csv

datas =[,

,]## 以字典方式寫入csv

with

open

('test_csv_data.csv'

,'w'

, newline='')

as f:

writer = csv.dictwriter(f,

['name'

,'age'])

# 標頭在這裡傳入,作為第一行資料

writer.writeheader(

)for row in datas:

writer.writerow(row)

# 還可以寫入多行

writer.writerows(datas)

## 以字典方式讀取csv

with

open

('test_csv_data.csv'

,'r'

)as f:

reader = csv.dictreader(f)

for row in reader:

print

(row[

'name'

], row[

'age'])

# name age

# bob 23

# jerry 44

# tom 15

# bob 23

# jerry 44

# tom 15

# 捕獲和報告錯誤:

import csv, sys

filename =

'test_csv_data.csv'

with

open

(filename, newline='')

as f:

reader = csv.reader(f)

try:

for row in reader:

print

(row)

except csv.error as e:

sys.exit(

'file {}, line {}: {}'

.format

(filename, reader.line_num, e)

)

csv模組的學習 Python

csv 逗號分隔值檔案格式,其檔案以純文字形式儲存 資料。csv檔案的格式非常簡單,類似乙個文字文件,每一行儲存一條資料,同一行中的各個資料通常採用逗號分隔。python中內建了csv模組,專門用於處理csv檔案的讀取和存寫,也可以使用pandas來處理資料量巨大的csv檔案。csv檔案的寫入 把自...

python之模組csv之CSV檔案一次寫入多行

coding utf 8 python 27 xiaodeng csv檔案一次寫入多行 import csv csv檔案,是一種常用的文字格式,用以儲存 資料,很多程式在處理資料時會遇到csv格式檔案 files open test.csv wb writer csv.writer files wr...

python 使用csv模組匯出csv檔案問題

python3中存csv亂碼的問題 with open filename,a newline encoding utf 8 sig as f 中文需要設定成utf 8格式 open 增加encoding得設定即可 python2不支援 python2中中文亂碼問題 用記事本開啟匯出得csv檔案,另存...