Python Forum

Full Version: Write to CSV
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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")
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
This looks like a homework assignment
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.
Don't start a new thread,when it's the same topic as in your other thread.
Nice catch, didn't see that.