首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

用python读取CSV的有关问题

2013-07-16 
用python读取CSV的问题CSV文件如下:col1, col2, col3 student id, student, name, scorepython程序如下:

用python读取CSV的问题
CSV文件如下:
col1, col2, col3 
student id, "student, name", score

python程序如下:
import csv

class CSVTest:
    def __init__(self, filename, sep=','):
        try:
            self.infile = open(filename, "rb")
            self.reader = csv.reader(self.infile, delimiter=',', quotechar='"')
            
            for row in self.reader:
                if len(row) > 0:
                    for col in row:
                        print "col:", col
        except Exception, e:
            print "Failed to load template: %s, %s" %(filename, e)
            raise
        finally:
            self.infile.close()
            
if __name__ == '__main__':
    obj = CSVTest("test.csv")

最后输出结果为:
col: col1
col:  col2
col:  col3 
col: student id
col:  "student
col:  name"
col:  score

一般CSV的标准规定,当字段中有分隔符(逗号)时,需要用双引号将该字段的内容包起来。我期望student, name 作为一个字段读出来,而不是两个字段。难道python的CSV不知道这个特性?
[解决办法]
文件打开方式换成 'r' 试试
[解决办法]
按照文本文件读取,然后用逗号分隔字符串可以吗
------解决方案--------------------


养成习惯查看文档先,http://docs.python.org/2/library/csv.html?highlight=csv#csv-fmt-params
默认就是delimiter=',', quotechar='"',貌似你的问题在于分隔符后的空白,试试:
self.reader = csv.reader(self.infile, skipinitialspace=True)

热点排行