dedpo dedpo - 7 months ago 14
Python Question

Python - export fields to a CSV

for i in tweets_df.ix[:,0]:
if regex_getter(i) != None:
city,state = regex_getter(i).split(',')
print(city,state)


I am essentially just trying to write city and state to csv. Print city and state prints exactly what i have below minus the headers

my csv should look like

City State
Burlington VT
Minneapolis MN
Bloomington IN
Irvine CA

Answer

You can use the csv module to do this:

writerow will take an iterable and write each item in the iterable in a separate column.

import csv
....
with open("test.csv", "w", newline='') as csvfile:
     writer = csv.writer(csvfile)
     #write header, or something
     for i in tweets_df.ix[:,0]:
          if regex_getter(i) != None:
              data = regex_getter(i).split(',')
              writer.writerow(data)