python讀取csv檔案

2021-09-24 23:46:01 字數 1654 閱讀 5721

csv格式資料

import csv
csv資料儲存,包括三種方式:

直接寫入csv檔案;

寫入:一條或者多條資料

import csv

header = ['line1','line2','line3']

rows = [[1,2,3],[4,5,6],[7,8,9]]

with open('test.csv','w') as f:

file = csv.writer(f)

file.writerow(header)

file.writerows(rows)

寫入字典:

寫入:包括寫入頭部,寫入字典型別內容

import csv

header = ['line1','line2','line3']

rows = ,,}

with open('dict.csv','w', newline='') as f:

file = csv.dictwriter(f,header)

file.writeheader()

file.writerows(rows)

讀取資料,讀取所有列資料,讀取某一列資料並列印

# 列印所有結果:

import csv

def readfilerows():

with open('test.csv','r') as f:

file = csv.reader(f)

for line in file:

print(line)

readfile()

# 如下型別結果:

['ip位址', '埠', '位址']

['115.53.18.58', '9999', '河南濮陽']

['218.91.112.161', '9999', '江蘇揚州']

['117.91.132.152', '9999', '江蘇揚州']

['114.230.69.167', '9999', '江蘇揚州']

['112.85.166.122', '9999', '江蘇南通']

['116.208.55.163', '9999', '湖北襄陽市宜城']

['222.189.190.187', '9999', '江蘇揚州']

['116.208.11.181', '9999', '湖北襄陽']

['180.119.141.239', '9999', '江蘇揚州']

# 列印第乙個字段:

def readfileitem():

with open('test.csv','r') as f:

file = csv.reader(f)

for line in file:

print(line[0])

readfile()

# 如下結果:

# ip位址

115.53.18.58

218.91.112.161

117.91.132.152

114.230.69.167

112.85.166.122

116.208.55.163

222.189.190.1

python讀取CSV檔案

reader讀取csv檔案,再用for迴圈遍歷 import csv with open customer.csv as f f csv csv.reader f for row in f csv print row 0 執行結果 id test 932467 1111 932468 2 93246...

python讀取csv檔案

在python裡面,讀取或寫入csv檔案時,首先要import csv這個庫,然後利用這個庫提供的方法進行對檔案的讀寫。0x01 獲取每一行 讀取csv檔案,用的是csv.reader 這個方法。返回結果是乙個 csv.reader的物件,我們可以對這個物件進行遍歷,輸出每一行,某一行,或某一列。如...

Python讀取複雜CSV檔案

class readcsv anchor 0 final def init self,path,head 0 quote 0 row tmp cell tmp cell channel file path,r data channel.readlines channel.close reg quot...