Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
writing numbers to csv file
#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


Messages In This Thread
writing numbers to csv file - by SchroedingersLion - Dec-19-2018, 10:51 AM
RE: writing numbers to csv file - by ODIS - Dec-19-2018, 11:13 AM
RE: writing numbers to csv file - by buran - Dec-19-2018, 11:33 AM
RE: writing numbers to csv file - by buran - Dec-19-2018, 12:47 PM
RE: writing numbers to csv file - by buran - Dec-19-2018, 12:58 PM
RE: writing numbers to csv file - by perfringo - Dec-20-2018, 10:48 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,441 Sep-27-2022, 01:38 PM
Last Post: buran
  Writing to json file ebolisa 1 1,053 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Writing to External File DaveG 9 2,596 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  Calcolate the average of numbers from a .txt file francescomiles 2 3,074 Mar-27-2021, 02:43 PM
Last Post: francescomiles
  Writing to file ends incorrectly project_science 4 2,779 Jan-06-2021, 06:39 PM
Last Post: bowlofred
  Writing unit test results into a text file ateestructural 3 4,841 Nov-15-2020, 05:41 PM
Last Post: ateestructural
  Writing to file in a specific folder evapa8f 5 3,515 Nov-13-2020, 10:10 PM
Last Post: deanhystad
  Read strings and numbers in columns from a file suvadip 4 2,983 Aug-11-2020, 09:37 PM
Last Post: suvadip
  Failure in writing binary text to file Gigux 7 3,897 Jul-04-2020, 08:41 AM
Last Post: Gigux
  writing data to a csv-file apollo 1 2,413 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