1

我确实有一个 CSV 文件行,如下所示

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

我想在第 4 列和第 5 列之间添加一个新列。我怎样才能做到这一点?

22727176549389059,1917,6544,**91999926**,new column,**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'
4

2 回答 2

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

于 2013-05-20T20:03:22.257 回答
1

这是一种使用csv.DictReaderand的方法DictWriter。我在StringIO这里使用该软件包进行演示。f将是您的文件连接,csv_out将是您的输出。我创建了一个包含 A 列和 B 列的两行 csv,然后在它们之间插入一个列 C,它们都是 -1。

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'
于 2013-05-20T20:02:12.733 回答