I am accessing the Twitter API using Python and the Tweets it is returning are formatted as follows:
'text': 'Sentence 1 of the tweet that needs '
'to continue onto the second line.\n'
'\n'
'Sentence 2 etc etc etc'
I want each Tweet to have its own line in the csv file I'm dumping them into but when I apply .strip() to the text section before writing it to the file, it still keeps the line breaks. My best guess is that it's due to the separated single quotes for each line of the tweet. Any tips to get it all on one line? Attached is the csv writing code:
fieldnames = results["data"][0].keys()
with open("file.csv", "w") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
for tweet in results["data"]:
tweet["text"] = tweet["text"].strip()
writer.writerow(tweet)
EDIT: I figured it out and it was a fairly simple combination of a few things: .replace instead of .strip and writing straight to the file instead of creating a csv write instance. Here is what the working code looks like:
with open("file.csv", "w") as f:
for tweet in results["data"]:
tweet["text"] = tweet["text"].replace("\n", "")
f.write(tweet["text"] + '\n')