Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何书写';文件3.csv';文件内容到现有csv文件到特定列?_Python_Python 2.7 - Fatal编程技术网

Python 如何书写';文件3.csv';文件内容到现有csv文件到特定列?

Python 如何书写';文件3.csv';文件内容到现有csv文件到特定列?,python,python-2.7,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

以下是我输入的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() 
我遇到以下错误:

MacBookPro:test$python three.py
回溯(最近一次呼叫最后一次):
文件“three.py”,第10行,在
行[7]=f1.readline()#编辑第8列
索引器:列表分配索引超出范围


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

如果要分配给
行[7]
请先尝试以下操作:

if len(row) < 8:
    row += [None] * (8 - len(row))
如果长度(行)<8:
行+=[无]*(8-列(行))
因此,您的内部循环可能需要如下所示:

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)
读取器中的行的
:
如果长度(世界其他地区)<8:
行+=[无]*(8-列(行))
新的_值=f1.readline().strip().split(','))
行[7:7+1+len(新的_值)]=新的_值
writer.writerow(行)

能否提供几行
文件4.csv
?重现错误会很有帮助。如果标题存在,也可以添加标题