1

I have been trying to save a list to a CSV for my adventure game I am working on but I can't seem to find anything that works online, this is the code I have,

import csv
testarray = ["Hello", "My", "Name", "is", "John"]
wtr = csv.writer(open ('test.csv', 'w'), delimiter=';', lineterminator='\n')
for x in testarray : wtr.writerow ([x])
for label in testarray:
  testarray.write([label])
print("Done!")

Sorry if this was set out poorly I'm kind of new to this. Thanks in advance for the help

4
  • 1
    What is the question? There is no question here. Commented Nov 23, 2019 at 15:36
  • @zvone - The question is simply how to write a list to a csv file. Commented Nov 23, 2019 at 15:41
  • 1
    @SvetlanaofVodianova If that was really the question, then the answer would be simply "read the csv documentation". There is an example there doing exctly that. The OP is having some trouble with it, but has not taken time to find out what it is that they want to ask. Commented Nov 23, 2019 at 15:49
  • You should clearly state your output first, so we can provide an acceptable answer. Commented Nov 23, 2019 at 16:25

3 Answers 3

6

Before I post an answer let me take the time to explain what you're doing wrong so you don't repeat the same bad habits.

This line could be written better:

wtr = csv.writer(open ('test.csv', 'w'), delimiter=';', lineterminator='\n')

In Python it can be written as:

with open('items.csv', 'w', newline='') as csvfile:

In your code sample, you never used with. It's a good time to read about why you should use it.

Under that you can specify how and what to write, like this:

item_writer = csv.writer(csvfile, delimiter=', quoting=csv.QUOTE_MINIMAL)

This for loop could be written better:

for label in testarray:
  testarray.write([label])

You don't need to surround the label variable with [] brackets because it's not a list. You are referencing items from the list.

It can be written like this:

for item in testarray:
    item_writer.writerow(item)

This may not be what you want, because it will write every item in the list on it's own line.

Putting everything together, we get:

import csv


def main():

    testarray = ["Hello", "My", "Name", "is", "John"]

    with open('test.csv', mode='w') as employee_file:
        employee_writer = csv.writer(employee_file, delimiter=',',  quotechar='"', 
                                     quoting=csv.QUOTE_MINIMAL)
        employee_writer.writerow(testarray)

    print("done")

 # Will output:
 # Hello,My,Name,is,John

if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, is there a way to make sure that every letter is not separated by a space? BTW this code is not my own, I copied it off of another question to see if it would work and it did not, clearly. 😂
You say "doesnt make sense" twice, but that's unfair. To focus on the first example; it does pass a file object to csv.writer(). Saying it doesn't make sense... doesnt make sense. It's not to your liking but that is different
@roganjosh - When I say it doesn't make sense, I mean two things, 1. no with statement, and 2. It's not written in a pythonic way, no indents by 4 spaces and everything is written in one line. The code might work, but it could be written better.
I won't disagree with that. But I'd caution against "doesn't make sense". It does make sense, it's just not best practice. I'm not jumping on welcoming wagon but it comes across as the whole approach is wrong
Thanks a lot for all the help everyone, I have managed to get my program to work now 😃
2

Try this:

import csv

testarray = ["Hello", "My", "Name", "is", "John"]

with open('test.csv', 'w', newline='') as csvfile:
    writer= csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(testarray)

this is from the page: CSV File Reading and Writing

Worth a read through so you understand why it works.

7 Comments

Thanks a lot for the quick reply, is there a way to make every element g o onto a different line?
Yes, simply loop through the testarray object and repeat the writer.writerow() with each element as write row adds another row with the thing you pass to it
Sorry, I don't understand, is it possible for you to give me a code example? No worries if not.
no worries. the answer SvetlanaofVodianova gave is the full answer and should accepted
@Lordimass - If you want every element on it's own line, then their is no need for csv. You just want to write a list of elements to a file.
|
1

I would use Pandas Dataframe to build the dataframe and save it to CSV. If you want elements from a list in separate line do this

import pandas as pd
df1 = pd.Dataframe(testarray)

If you want all elements of a list in a single row do this

df1 = pd.DataFrame([testarray])

save it as

df1.to_csv("my_test.csv", index = False)

you can add column names in dataframe if you want.

If you have list of list as follows:

list_of_list = [['A', 15], ['B', 30], 
       ['C', 45], ['D', 22]] 

You can simply perform same as follows, with labelled columns

df_again = pd.DataFrame(list_of_list, columns =['letter', 'number']) 
df_again.to_csv("new_one.csv", index = False)

2 Comments

all that happens when I run this code is that it say that pandas is not a valid module
You need to install pandas, you can find here: pandas.pydata.org/pandas-docs/stable/install.html

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.