Write to csv: columns are shifted when item in row is empty (Python) -


basic read, al ok:

with open('kres.csv', newline='') f:     reader = csv.reader(f, quoting=csv.quote_all)     row in reader:         print(row)         kres.append(row) 

here writing csv, columns shifted when field (item) in row empty, that's (i assume) because program doesn't know how many columns in file , writes 1 one.
want not skip empty field, want write default character or none. don't know how check field empty.

with open('kres2.csv', 'w', newline='') f:    # use 'w' mode in 3.x     writer = csv.writer(f)     writer.writerows(kres) 

python 3.3.2 on windows 7

edit: trying chak every field in list, not working

with open('article_all_krestianin_ru.csv', newline='') f:     reader = csv.reader(f, quoting=csv.quote_all)     row in reader:         in row:             if == '':                 = '-'             print(row)         krestianin.append(row) 

edit 2: ['А теперь - про язык;Окт 21', ' 2008;Окт 21', ' 2008А теперь - про язык спрашивала', ' как ;http://www.krestianin.ru/articles/5541.php']

this console, 4 items in place (delimiter ;). of items can missing, 1 or 2, if 2 of 4 missing want put "-" on places

i think don't understand how csv module works in python. let's kres.csv file has data in it:

1,2,3,4,5,6,7 a,b,c,d,e,f,g 

then when execute code:

import csv  kres = []  open('kres.csv') f:     reader = csv.reader(f, quoting=csv.quote_all)     row in reader:         print(row)         kres.append(row) 

the output be:

['1', '2', '3', '4', '5', '6', '7'] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 

so gettin lists, each list row read.

if have data in kres.csv file:

1,2,3,5,6,7 a,b,c,d,e,f,g 

and need output this:

['1', '2', '3', '-', '5', '6', '7'] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 

then need write check, first check how many elements in row (in case if it's less 7 misssing element(s). after need find element missing. need know 4 (as in example), should after 3 , before 5.

you can write checks using regex (of course depends on data have in csv file) , have check each element (is elemtn in right column, list possition).

you can programmatically, not using csv module.


the empty element in csv file presented this:

1,2,3,,5,6,7 a,b,c,d,e,f,g 

so output of code be:

['1', '2', '3', '', '5', '6', '7'] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 

,, , '', empty element


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -