如何使用python读取csv文件 [英] How to read a csv file with python
本文介绍了如何使用python读取csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图读取一个csv文件,但它不工作。
我可以读取我的csv文件,但是当我看到我读到的,那里的值之间的空格。
I'm trying to read a csv file but it doesn't work. I can read my csv file but when I see what I read, there where white space between values.
这是我的代码
# -*- coding: iso-8859-1 -*-
import sql_db, tmpl_macros, os
import security, form, common
import csv
class windows_dialect(csv.Dialect):
"""Describe the usual properties of unix-generated CSV files."""
delimiter = ','
quotechar = '"'
doublequote = 1
skipinitialspace = 0
lineterminator = 'n'
quoting = csv.QUOTE_MINIMAL
def reco(d):
cars = {210:'"', 211:'"', 213:"'", 136:'à', 143:'è', 142:'é'}
for c in cars:
d = d.replace(chr(c),cars[c])
return d
def page_process(ctx):
if ctx.req_equals('catalog_send'):
if 'catalog_file' in ctx.locals.__dict__:
contenu = ctx.locals.catalog_file[0].file.read()
#contenu.encode('')
p = csv.reader(contenu, delimiter=',')
inserted = 0
modified = 0
(cr,db) = sql_db.cursor_get()
for line in p:
if line:
logfile = open('/tmp/test.log', 'a')
logfile.write(line[0])
logfile.write('\n')
logfile.write('-----------------------------\n')
logfile.close()
推荐答案
我更喜欢使用numpy的genfromtxt,而不是标准的csv库,因为它产生numpy的recarray,这是干净的数据结构,类似对象。
I prefer to use numpy's genfromtxt rather than the standard csv library, because it generates numpy's recarray, which are clean data structures to store data in a table-like object.
>>> from numpy import genfromtxt
>>> data = genfromtxt(csvfile, delimiter=',', dtype=None)
# data is a table-like structure (a numpy recarray) in which you can access columns and rows easily
>>> data['firstcolumn']
<content of the first column>
这篇关于如何使用python读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文