Python print to csv in iteration, save rows without line spaces

Question:

Hello I will save this output to a csv file after iteration, print is ok, but csv not.
Below are the print output

1580933840499281920 2022-10-14 14:49:34+00:00 illiabogdanov en RT @alexstubb: Dear @elonmusk, the war in Ukraine is about life and death, freedom and control, democracy and autocracy. 

1580933840448540672 2022-10-14 14:49:34+00:00 lies_das de RT @KPosmik: Wir haben uns entschieden, diese Szene von der Demo der #AfD #b0810 zu zeigen, um mit dem Vorurteil aufzuräumen, die #Luegenpr…
1580933839823679488 2022-10-14 14:49:34+00:00 JaviMac10 en RT @dim0kq: 0. I admire the actions of SpaceX of enabling StarLink service in Ukraine. It is a true game changer for Ukrainian army in the…
1580933839748145155 2022-10-14 14:49:34+00:00 LovelyLassSandy en @elonmusk Please consider continuing your Starlink platform in Ukraine! Can you work out a way to make this a charitable contribution for which you receive substantial tax breaks. Do not leave these families disconnected! Starlink has been a God to Ukraine!`

Python code:

for tweet in tweets:
    print(tweet.id, tweet.created_at, users[tweet.author_id].username, tweet.lang, tweet.text)
# Make a new file
    with open("test_file.csv", "w") as my_file:
            writer = csv.writer(my_file)
            writer.writerows(tweet.id, tweet.created_at, users[tweet.author_id].username, tweet.lang, tweet.text)

error:

 writer.writerows(tweet.id, tweet.created_at, users[tweet.author_id].username, tweet.lang, tweet.text)
TypeError: writerows() takes exactly one argument (5 given)
Asked By: Giuse Esse

||

Answers:

You need to provide writer.writerows(someiterable).

Iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables. In short and simpler terms, iterable is anything that you can loop over.

So it should look like this.

newUser = [tweet.id, tweet.created_at, users[tweet.author_id].username, tweet.lang, tweet.text]
writer.writerows(newUser)
Answered By: JPC
import csv
with open("test_file.csv", "w") as my_file:
    writer = csv.writer(my_file)
    for tweet in tweets:
        writer.writerow([tweet.id, tweet.created_at,users[tweet.author_id].username, tweet.lang, tweet.text])
Answered By: Giuse Esse
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.