Python實現讀取及寫入csv檔案的方法示例

2022-10-04 11:39:13 字數 998 閱讀 2103

新建csvdata.csv檔案,資料如下:

具體**如下:

# coding:utf-8

import csv

# 讀取csv檔案方式1

csvfile = open("csvdata.csv", "r")

reader = csv.reader(csvfile) # 返回的是迭代型別

data =

for item in reader:

print(item)

data.append(item)

print(data)

csvfile.close()

# 讀取csv檔案方式2

with open("csvdata.csv", "r") as csvfile:

reader2 = csv.reader(csvfile) # 讀取csv檔案,返回的是迭代型別

for item2 in reader2:

print(item2)

csvfile.close()

# 從列表寫入csv檔案

csvfile2 = open('csvfile2.csv','w', newlimmscdybne='') # 設定newline,否則兩行之間會空一行

writer = csv.writer(csvfile2)

m = len(data)

for i in range(m):

writer.writerow(datmmscdyba[i])

csvfile2.close()

# 從字典寫入csv檔案

dic = www.cppcns.com

csvfile3 = open('csvfile3.csv','w', newline='')

writer2 = csv.writer(csvfile3)

for key in dic:

writer2.writerow([key, dic[key]])

csvfile3.close()

python將二維列表內容寫入和讀取 csv檔案

coding utf 8 import csv list 1,2 3,4 5 6,7 8 89,55 66666,5 張三 李四 王五 tom f open 222.csv w writer csv.writer f for i in list writer.writerow i f.close 效...

python(檔案讀取寫入)

python讀寫檔案 1.open 使用open開啟檔案後一定要記得呼叫檔案物件的close 方法。比如可以用try finally語句來確保最後能關閉檔案。file object open thefile.txt try all the text file object.read finally ...

Python 讀取寫入txt

讀取 read readline readlines with open txtdata.txt r as f 開啟檔案 data f.read read 一次性讀取文字內容,以字串形式返回 print data,type data with open txtdata.txt r as f 開啟檔案...