Python Forum
Write to CSV - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Write to CSV (/thread-3034.html)



Write to CSV - arsenal88 - Apr-25-2017

I have a list of values [abc123, abc123, abc123, abc123, etc..]

I want to input that list into a CSV whereby the first 3 characters of each index are in the first column.

i.e 
 list = [abc123, abc123, abc123, abc123]


for i in list:
     first_3 = i[:3]
     the_rest =i[3:]
 

I need the data structured in the cvs like follows:


col1      col2   col3   col4
abc         1      2      3
abc         1      2      3
abc         1      2      3


I've created a csv with headers as follows:

file = open('test.cv', 'w')
file.write('First col')
for h in range(0, 4):
      file.write('Col' + str(h) + ",")
file.write('\n')
I need to iterate through the list but I'm stuck on how to place rows and columns.  Keep getting stuck. The closest to any solution i've got to is this but its way off..

for i in range(0, len(list)
      for j in range(0, len(list[i]):
            file.write(list[i][j] + ","
file.write("\n")



RE: Write to CSV - volcano63 - Apr-25-2017

Wall file, list are Python function names - please, don't overshadow those with your variables.
Every second post here - me think  Angry - is about iterating over lists directly.
If you want to create a string with comma-separated list elements, use join method
','.join(data)
PS You didn't close bracket in line 3 - and you are supposed to close line with EOL - you write it outside the outermost loop, thus not separating rows


RE: Write to CSV - wavic - Apr-26-2017

This looks like a homework assignment


RE: Write to CSV - sparkz_alot - Apr-26-2017

Maybe it's just me, but I don't understand why you are trying to format a .csv file.  If you want to format a file, why not just save to a text file.  The purpose of the .csv is to hold data using a separater (usually a comma, but can just about be anything). Formatting would take place when you retrieve the data from the file.


RE: Write to CSV - snippsat - Apr-26-2017

Don't start a new thread,when it's the same topic as in your other thread.


RE: Write to CSV - sparkz_alot - Apr-26-2017

Nice catch, didn't see that.