python csv contactenation问题

时间:2015-10-15 01:15:42

标签: python csv python-3.x

HI我试图将3列合并到csv文件中并且我得到一个IndexError:list index超出范围。我有9列,分隔符是|

import csv

f = open('C:\\diners\\bacon.csv')
csv_f = csv.reader(f)
attendee_emails1 = []
for row in csv_f:
   attendee_emails1.append(row[5]+row[6]+row[7])

print (attendee_emails1)  

我做得不对?

1 个答案:

答案 0 :(得分:0)

在将文件对象传递给reader方法时,还需要指定分隔符。

csv_f = csv.reader(f, delimiter="|")

代码:

import csv
f = open('/home/avinash/Desktop/dh.csv')
csv_f = csv.reader(f, delimiter="|")
attendee_emails1 = []
for row in csv_f:
   attendee_emails1.append(row[5]+row[6]+row[7])

print (attendee_emails1) 

示例:

$ cat dh.csv
1|2|3|4|5|6|7|8|9
$ python script.py
['678']