Python CSV错误

时间:2016-09-22 14:33:50

标签: python python-2.7 csv

大家好我在制作一个小型程序来排序大型CSV文件时一直收到此错误,下面是我的代码和错误,我做错了什么?

if selection:
        for stuff in stuffs:

            try:
                textFile = open("output.txt",'w')
                mycsv = csv.reader(open(stuff))
                d_reader = csv.DictReader(mycsv)
                headers = d_reader.fieldnames <-- Error happens here
                if selection in headers:
                    placeInList = headers.index(selection)

                    #placeInList = selection.index(selection)
                    for selection in tqdm(mycsv, desc='Extracting column values...', leave = True):
                        textFile.write(str(selection[int(placeInList)])+'\n')
                    print 'Done!'
                    textFile.close()
                    sys.exit()
            except IOError:
                print 'No CSV file present in directory'
                sys.exit()
    else:
        sys.exit()

错误:

Traceback (most recent call last): 
File "postcodeExtractor.py", line 27, in <module> headers = d_reader.fieldnames 
File "C:\Python27\lib\csv.py", line 90, in fieldnames self._fieldnames = self.reader.next() 
TypeError: expected string or Unicode object, list found

1 个答案:

答案 0 :(得分:0)

而不是

mycsv = csv.reader(open(stuff))
d_reader = csv.DictReader(mycsv)

你想要

d_reader = csv.DictReader(open(stuff))

第一行是问题。