python 2.7 - Copy columns to another csv file -


i have csv table , want copy columns csv table.

import csv path1='1.csv' path2='2.csv' outdata=[] open(path1,'rb') input ,open (path2,'wb') output:     reader=csv.reader(input)     writer=csv.writer(output,delimiter=' ')     row in reader:         outdata.append(row[0])         outdata.append(row[1])     write.writerows(outdata) 

here original table(some cells null):

 b c d f  1   3   5    e   t  5   4   6 

but new table in 1 column:

a 1  5 b  e 

what want:

a b 1     e 5 

your situation complex. in case, space both delimiter & column entry!! afaik, confuse python interpreter. see if can avoid that.

i have assumed ' ' (i.e., space) not column entry instead '' (i.e., empty string). 1.csv becomes:

$> cat 1.csv  b c d f 1  3  5  e  t 5  4  6 

if scenario, code work:

import csv path1='1.csv' path2='2.csv' outdata = [] input_file = open(path1,'rb') output = open (path2,'wb')  reader=csv.reader(input_file, delimiter=' ') writer=csv.writer(output,delimiter=' ') row in reader:     print("row: ", row)     outdata.append([row[0], row[1]]) print(outdata) writer.writerows(outdata) 

so couple of changes script:

  1. you have specify delimiter reader well. default delimiter ','
  2. since use csv.writerows(), input list of list & each list row. so, prepare list of list & see values properly.

finally, output of above python script wanted:

$> cat 2.csv ('row: ', ['a', 'b', 'c', 'd', 'f']) ('row: ', ['1', '', '3', '', '5']) ('row: ', ['', 'e', '', 't']) ('row: ', ['5', '', '4', '', '6']) [['a', 'b'], ['1', ''], ['', 'e'], ['5', '']] b 1   e 5  

i have added lot of prints can understand script better. :)


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -