在python中移动csv中第一行的列

时间:2017-07-10 06:43:47

标签: python-3.x

我有一个csv文件,其中第一行有列名。我想只排除第一行(A1)第一列以外的列名称。

我的CSV看起来像:

"name","A","B","C","D"  
"Romi", 5,  6,  3,  6  
"Meli", 5,  8,  9,  7  
"John", 3,  6,  8,  9  

我希望它是这样的:

"name","C","A","D","B"  
"Romi", 5,  6,  3,  6  
"Meli", 5,  8,  9,  7  
"John", 3,  6,  8,  9  

这是我的代码:

infile = open('data.csv', 'r')

table = []

for row in csv.reader(infile, delimiter = ','):
    table.append(row)
infile.close()


table_one = ' '.join(table[0])
table_one = table_one.split(' ')
table_one = table_one[1:10]
for i in range(1,11):
    random.shuffle(table_one)
    table[0] = table_one
    print table[0]

它是这样打印的:

"C","A","D","B"  
"Romi", 5,  6,  3,  6  
"Meli", 5,  8,  9,  7  
"John", 3,  6,  8,  9  

我正在使用python 3.0。

3 个答案:

答案 0 :(得分:0)

import csv 
infile = open('S228c_foldvalues_modified.csv', 'r')

table = []

for row in csv.reader(infile, delimiter = ','):
    table.append(row)
infile.close()


table_one = table[0]
table_one[1], table_one[2], table_one[3], table_one[4] = 
table_one[3], table_one[1], table_one[4], table_one[2]
table[0] = table_one

print(table)

with open('outfile.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(table)

只需交换列表中的第一行项目并写回文件。希望这有帮助。

答案 1 :(得分:0)

table = []
with open('S228c_foldvalues_modified.csv', 'r') as infile:
    for row in csv.reader(infile, delimiter = ','):
        table.append(row)

table_one = table[0][1:]
random.shuffle(table_one)
table_one = [table[0][0]]+table_one
print (table_one)

答案 2 :(得分:0)

这里我已经解决了它

table_one = table[0][2:]
for i in range(1,11):  
    random.shuffle(table_one)
    table[0][2:] = table_one
    print table[0]