Python讀取複雜CSV檔案

2021-06-07 19:01:20 字數 2371 閱讀 8266

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_quote = re.compile('\"')

rm_quote = re.compile(r'"([\s\s]*)"')

db_quote = re.compile(r'""')

for line in data:

quote += len(reg_quote.findall(line))

if quote%2 == 0:

quote = 0

row_tmp += line.strip('\n')

row_tmp = row_tmp.split(',')

for col in row_tmp:

quote+=len(reg_quote.findall(col))

if quote%2 == 0:

cell_tmp += col

cell_tmp = rm_quote.sub(r'\1',cell_tmp)

cell_tmp = db_quote.sub('\"',cell_tmp)

cell_tmp = ''

quote = 0

else:

cell_tmp += col+','

cell =

row_tmp = ''

else:

row_tmp+=line

def getcell(self,row,col):

return readcsv.final[row][col]

def getvalue(self, title):

return self.getcell(readcsv.anchor, readcsv.final[0].index(title))

def next(self):

if self.done() != true and readcsv.anchor < len(readcsv.final)-1:

readcsv.anchor += 1

def done(self):

if readcsv.anchor == len(readcsv.final)-1:

return true

else:

return false

def reset(self):

readcsv.anchor = 0

csv file:

name

ageaddress

zhang_san

13address1:

1. aaaaa

2. aaad "bbbb",

3. bacad,

adfa"aaa".

li_si

14address2, ***x

aaaa"

bbbbb".,

wang_wu

15address3

example:

p = readcsv('c:/csvfile.csv')

print p.getcell(1,2)

output:

address1:

1. aaaaa

2. aaad "bbbb",

3. bacad,

adfa"aaa".

p.next()

print p.getvalue('name')

p.next()

print p.getvalue('address')

output:

zhang_san

address2, ***x

aaaa"

bbbbb".,

p.done()

p.next()

p.next()

p.next()

p.done()

output:

false

true

p.next()

p.next()

print p.getvalue('name')

p.reset()

print p.getvalue('name')

output:

li_si

name

python讀取csv檔案

csv格式資料 import csvcsv資料儲存,包括三種方式 直接寫入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.w...

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的物件,我們可以對這個物件進行遍歷,輸出每一行,某一行,或某一列。如...