如何写' file3.csv'将现有csv文件的内容归档到特定列?

时间:2017-05-16 02:25:29

标签: python python-2.7

以下是我的输入csv文件内容

file3.csv:

a,ab
b,cd
c,nav
d,test
name,port

我想将其写入现有的csv文件中,使用特定的列号。

例如:

I want to write, a,b,c,d,name into a column number --- AA
And I need to write ab,cd,nav,test,port into a column number ---AB

Python脚本:

import csv

f1 = open ("file3.csv","r") # open input file for reading

with open('file4.csv', 'wb') as f: # output csv file
    writer = csv.writer(f)
    with open('file3.csv','r') as csvfile: # input csv file
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:  
            row[7] = f1.readline() # edit the 8th column 
            writer.writerow(row)
f1.close() 

我收到以下错误:

  

MacBook-Pro:测试$ python three.py
  追溯(最近的呼叫最后):
  文件" three.py",第10行,在        row [7] = f1.readline()#编辑第8列
  IndexError:列表分配索引超出范围

1 个答案:

答案 0 :(得分:0)

您不能将索引用于列表中尚不存在的元素。在将元素分配给特定索引之前,您需要增加行的长度。

如果您想分配到if len(row) < 8: row += [None] * (8 - len(row)) ,请先尝试:

for row in reader:
    if len(row) < 8:
        row += [None] * (8 - len(row))
    new_values = f1.readline().strip().split(',')
    row[7:7+1+len(new_values)] = new_values
    writer.writerow(row)

因此,您的内部循环可能需要看起来像:

"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\msbuild.exe" "C:\WorkArea\xxxxx\_work\1\s\xxxxx\Main\Source\xxxx.sln" /nologo /nr:false /t:"Clean" /dl:CentralLogger,"C:\WorkArea\xxxxx\tasks\MSBuild\1.0.55\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";"RootDetailId=30268741-631d-4ac8-b4d2-d5b2774b61e7|SolutionDir=C:\WorkArea\xxxxx\_work\1\s\xxxx\Main\Source"*ForwardingLogger,"C:\WorkArea\xxxxx\tasks\MSBuild\1.0.55\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll"  /p:platform="Any CPU" /p:configuration="Debug" /p:_MSDeployUserAgent="TFS_6e1df8d0-1a29-425d-803c-d70779d0c76a_build_3175_345868"