python - 如何从 CSV 移动表格的列?

标签 python csv

我已经为 CSV 数据添加了新标题(参数),并且必须计算新参数,因此它需要保持为空。我需要将整个数据向右移动一列,但我不知道如何使用 python v 3.2 谁能帮帮我?

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

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)

最佳答案

要插入一个空列,您唯一需要做的就是向每一行添加一个初始 ,。这是执行此操作的一些代码 - 您甚至不需要 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()

关于python - 如何从 CSV 移动表格的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30676969/

相关文章:

python - 拥有多个 tf.Graph 有什么意义?

python - 在 Tkinter 程序中运行我的程序

python - 将当前日期与 CSV 文件匹配并打印匹配项

java - 如何根据java中的双引号分隔符将多个List<String>元素合并为一个

c# - 将棘手的字符串转义为 CSV 格式

python - 棋盘上的 8 个皇后 | python |内存错误

python - Pycharm 在 Python-Django 项目的 Debug模式下给出错误 "TypeError: ' NoneType' object is not callable"

python - 如果 django 中重置密码电子邮件链接错误,则页面未找到(404)错误

python - 使用新行读取 csv 文件

php - 在 CodeIgniter 中跳过 csv_from_result() 中的第一行