如何在CSV文件中添加其他列?

时间:2013-05-20 19:43:12

标签: python python-2.7

我的CSV文件行如下

  

22727176549389059,1917,6544,的 91999926,266392261 下,53972147,2131,太阳   2013年4月28日21:00:44

我想在第4列和第5列之间添加一列。我怎样才能做到这一点。有什么帮助吗?

  

22727176549389059,1917,6544, 91999926 ,新栏目, 266392261 ,53972147,2131,Sun Apr 28 21:00:44 PDT 2013

我知道如何在最后追加。但这没有帮助......

import csv
all = []
with open('fileinput','rU') as csvinput:
  reader = csv.reader((line.replace('\0','') for line in csvinput), delimiter=',')
  line = 0;
  try:
    for row in reader:
  #    row.append('')
      if '\0' in row: continue
      if not row: continue
      row.append('#3')
      all.append(row)
      except csv.Error, e:
          print 'Error'

2 个答案:

答案 0 :(得分:2)

将行视为列表,您可以使用以下

>>> a = [1,2,3,4,5]
>>> a = a[:3] + [9,8,7] + a[3:]
>>> a
[1, 2, 3, 9, 8, 7, 4, 5]

>>> a = [1,2,3,4,5]
>>> a.insert(3, 9)
>>> a
[1, 2, 3, 9, 4, 5]

然后创建一个新的csv

答案 1 :(得分:1)

以下是使用csv.DictReaderDictWriter的方法。我在这里使用StringIO包进行演示。 f将是您的文件连接,csv_out将是您的出局。我创建了一个包含A列和B列的两行csv,然后在它们之间插入一个C列。

import StringIO
import csv

orig_csv_text = """A,B
1,2
3,4
"""
# behaves like a file connection to the above string
f = StringIO.StringIO(orig_csv_text)

# empty out buffer, behaves like a new file connection
csv_out = StringIO.StringIO('')

# new column to add and the name
new_col = [-1,-1]
new_col_name = 'C'

# extract original header names from first row of csv
orig_names = [name.strip() for name in f.readline().split(',')]
# read the rows into a list
rows = list(csv.DictReader(f, fieldnames=orig_names))
new_names = orig_names
# take the original names and insert the new column where you want it. 
# here I insert after the first column.
new_names.insert(1, 'C')
# create a writer object using the new names
writer = csv.DictWriter(csv_out, fieldnames=new_names, lineterminator='\n')
writer.writeheader()
# for each row in the original csv, add the new value and write it to csv_out.
for row, new_val in zip(rows, new_col):
    row[new_col_name] = new_val
    writer.writerow(row)

csv_out.getvalue()
# 'A,C,B\n1,-1,2\n3,-1,4\n'