Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write to CSV
#1
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")
Reply
#2
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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
This looks like a homework assignment
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
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.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#5
Don't start a new thread,when it's the same topic as in your other thread.
Reply
#6
Nice catch, didn't see that.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020