1

Im trying to write a function that writes multiple lists to a singular csv file and i am able to get the column titles to write, but not any of the data. My data is in lists that are similar to this [92,3801,2,22,4] and the second is [3.0,2,23,5] and im looking for guidance on this. Thank you!

import csv
def export_results(number_of_words_sentence,mean_word_per_sentence):
    with open("assignment_7_results.csv", "w", newline="") as Assignment_7_results:
        writer = csv.writer(Assignment_7_results)
        writer.writerow(["Number of Words", "Words/Sentence"])
    # Our .csv file will have two columns, one for the dict keys and one for the dict values
        writer.writerows(number_of_words_sentence)
        writer.writerows(mean_words_per_sentence)
1
  • 1
    As the name implies, writerows writes rows, not columns. You'll have to zip and iterate over each pair of elements in turn, and call writerow Commented Oct 22, 2017 at 0:02

2 Answers 2

1

As the name implies, writerows writes rows, not columns. Furthermore, your lists are not equally sized, so you'll need to do something to account for that. The standard way of handling such a thing is using itertools.zip_longest.

from itertools import zip_longest # izip_longest in python2.x

with open("assignment_7_results.csv", "w") as f:
    w = csv.writer(f)
    w.writerow(["Number of Words", "Words/Sentence"])
    for x, y in zip_longest(number_of_words_sentence, mean_word_per_sentence):
        w.writerow([x, y])
Sign up to request clarification or add additional context in comments.

8 Comments

I tried adding this to my code and it did not produce an output
@J.McCraiton Okay. And? Do you think that piece of information can help me understand what's wrong?
Currently it produces the headings and with no columns underneath it. Sorry, should have been a little more descriptive. My bad man.
@J.McCraiton I see. That's a little weird. Are you sure your lists are being passed with data?
Im 95% sure. I am using lists generated from previous functions that I am able to print out to view the results and inputting those lists as the parameters
|
0

Try this to store the data in csv file with multiple list of different length. Here I tried to give header same as A and B as list name.

import pandas as pd

A = ['Apple', 'Dog']

B = ['Cat', 'OWL', 'PEACOCK']

dict_1 = {'A': A, 'B': B}

df = pd.DataFrame.from_dict(dict_1, orient='index')

dt = df.transpose()

dt.to_csv('myfile.csv', index=False, header=True,  encoding='utf-8')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.