How to transfer table columns from CSV?
I added new headers (parameters) for the CSV data and the new parameter needs to be calculated to keep it blank. I need to move all data to the right by one column and I cannot figure out how with python v 3.2 Can anyone help me?
So when I open my python CSV file with excel it gives me something like this (super simplified version, I have thousands of rows and columns)
P1 P2 P3 P4 P5 ...
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
... ...
And I want to change that; leaving P1 blank.
P1 P2 P3 P4 P5 ...
1 2 3 4
1 2 3 4
1 2 3 4
This is the code I have so far. I just want to move this data to the right one column. Can anyone help me? Thanks in advance!
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)
source to share
The only thing you need to do to insert an empty column is to add a leading one to each row ,
. Here's the code for that - you don't even need a CSV module for that. From your example, I assume you don't want to change the titles, right?
#!/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()
source to share