如何从CSV中移动表格的列?

时间:2015-06-05 22:51:40

标签: python csv

我已经为CSV数据添加了新的标题(参数),并且必须计算新参数,因此需要保持为空。我需要将整个数据向右移动一列,我无法弄清楚如何使用python v 3.2 有人可以帮帮我吗?

所以当我用excel打开我的python CSV文件时,它给了我这样的东西(超简化版本,我有数千行和列)

P1 P2 P3 P4 P5 ...

1  2  3  4  5
1  2  3  4  5
1  2  3  4  5

我想改变它;让P1空着。

P1 P2 P3 P4 P5 ...

    1  2  3  4  
    1  2  3  4   
    1  2  3  4  

这是我到目前为止所获得的代码。我只想将数据向右移一列。有人可以帮帮我吗? 提前谢谢!

    import csv

    # reads the input and spits out the output
    with open ('DownloadDB_CSV1.csv', 'r') as csvinput:
         with open ('outputCSV.csv', 'w', newline ='') as csvoutput:
             reader = csv.reader(csvinput, delimiter = ',')
            writer = csv.writer(csvoutput,  delimiter = ',')
    all = []
    row = next(reader)
    row.insert(0,'GenomePosition')
    all.append(row)



    for row in reader:
        all.append(row)
        contents = row[0::] # sepearte it to a variable
    writer.writerows(all)

1 个答案:

答案 0 :(得分:0)

要插入空列,您唯一需要做的就是在每行添加一个初始,。这里有一些代码 - 您甚至不需要CSV模块来执行此操作。从你的例子来看,我想你不想转移标题,对吗?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  test_csv.py
#  
#  Copyright 2015 John Coppens <john@jcoppens.com>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#  
#  

SEPARATOR = ","

def add_empty(infile, outfile):
    with open(outfile, "w") as outf:
        with open(infile, "r") as inf:
            line = inf.readline()       # Copy the header
            outf.write(line)

            while True:
                line = inf.readline()
                if line == "": break    # EOF
                outf.write("" + SEPARATOR + line)

def main():
    add_empty("test.csv", "testshifted.csv")
    return 0

if __name__ == '__main__':
    main()