Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
writing numbers to csv file
#1
Greetings,

can someone tell me wether the following is correct?
I have float values stored in two lists, namely x2 and y2.
I want to print a csv file with delimiter " ", in which the i-th element of x2 stands next to the i-th element of y2 in the i-th row.

with open(outputname, mode='w') as csv_output:
	result_writer=csv.writer(csv_output, delimiter=" ")
	for j in range(len(x2)):	
		result_writer.writerow(x2[j], y2[j])
outputname is a string of the name of the outputfile that is to be created, namely "outputfile.csv".



Regards!
Reply
#2
I would say that you have to pass the list of columns to the writerow() function:

import csv

x2 = [1, 2, 3]
y2 = ["a", "b", "c"]

with open("./outputfile.csv", "w") as file:
    csv_writer = csv.writer(file, delimiter=" ")
    for i in range(0, len(x2)):
        csv_writer.writerow(
            [
                str(x2[i]),
                str(y2[i])
            ]
        )
Reply
#3
with open(outputname, mode='w') as csv_output:
    result_writer=csv.writer(csv_output, delimiter=" ")
    
    # option 1
    for nums in zip(x2, y2):    
        result_writer.writerow(nums) # here you need to pass iterable, e.g. list, tuple, etc.
        
    # option 2 - alternative to option 1
    data = (nums for nums in zip(x2, y2))
    result_writer.writerows(data) # here you need to pass list of lists, etc. Here we pass generator expression that will yield tuples
EDIT:Option 2 can be simplified further
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
(Dec-19-2018, 11:33 AM)buran Wrote:
with open(outputname, mode='w') as csv_output:
    result_writer=csv.writer(csv_output, delimiter=" ")
    
    # option 1
    for nums in zip(x2, y2):    
        result_writer.writerow(nums) # here you need to pass iterable, e.g. list, tuple, etc.
        
    # option 2 - alternative to option 1
    data = (nums for nums in zip(x2, y2))
    result_writer.writerows(data) # here you need to pass list of lists, etc. Here we pass generator expression that will yield tuples

Why so complicated? What would be the problem with ODIS' solution?
Reply
#5
(Dec-19-2018, 12:31 PM)SchroedingersLion Wrote: Why so complicated? What would be the problem with ODIS' solution?
It's simpler than ODIS solution - 2 lines (use either option1 or option2).

What I don't like with ODIS' solution (no offence, please):
1. using range(len(iterable)) to loop - read https://python-forum.io/Thread-Basic-Nev...n-sequence
2. why construct list in each iteration, when you can use zip to combine both lists and iterate simultaneously over both lists?
3. no need to cast variables to str
4. if we write ODIS' solution on two lines
for i in range(0, len(x2)):
    csv_writer.writerow([str(x2[i]), str(y2[i])])
or even if we look at it as is, which one is more readable? Compare with

for nums in zip(x2, y2):    
    result_writer.writerow(nums)
or

data = (nums for nums in zip(x2, y2))
result_writer.writerows(data)
Of course, it works - feel free to use any one you like most.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Thank you, I will give it a try this afternoon!
Reply
#7
Actually option2 can be simplified even further
data = zip(x2, y2)
result_writer.writerows(data)
or even as one-liner
result_writer.writerows(zip(x2, y2))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
For SchroedingersLion sake I add one additional tidbit to consider when comparing those two solutions:

(Dec-19-2018, 12:58 PM)buran Wrote: Actually option2 can be simplified even further
data = zip(x2, y2)
result_writer.writerows(data)
or even as one-liner
result_writer.writerows(zip(x2, y2))

zip() produces iterator and you can consume it only once. Depending on your needs and in order to avoid nasty surprises you should be aware of following (expected) behaviour:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)       # iterator created
>>> list(zipped)             # iterator consumed
[(1, 4), (2, 5), (3, 6)]
>>> list(zipped)             # exhausted iterator           
[]
>>> list(zip(x, y))          # iterator created and consumed
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(x, y))          # iterator created again and consumed
[(1, 4), (2, 5), (3, 6)]    
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,404 Sep-27-2022, 01:38 PM
Last Post: buran
  Writing to json file ebolisa 1 1,029 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Writing to External File DaveG 9 2,539 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  Calcolate the average of numbers from a .txt file francescomiles 2 3,040 Mar-27-2021, 02:43 PM
Last Post: francescomiles
  Writing to file ends incorrectly project_science 4 2,713 Jan-06-2021, 06:39 PM
Last Post: bowlofred
  Writing unit test results into a text file ateestructural 3 4,786 Nov-15-2020, 05:41 PM
Last Post: ateestructural
  Writing to file in a specific folder evapa8f 5 3,460 Nov-13-2020, 10:10 PM
Last Post: deanhystad
  Read strings and numbers in columns from a file suvadip 4 2,939 Aug-11-2020, 09:37 PM
Last Post: suvadip
  Failure in writing binary text to file Gigux 7 3,844 Jul-04-2020, 08:41 AM
Last Post: Gigux
  writing data to a csv-file apollo 1 2,386 Jul-03-2020, 02:28 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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