0

I would like to save my strings into a csv file. Given the code below, there is a closed file issue, how can I save the list of strings into csv file? I don't understand why is this not working.

Code

import csv
with open('onehot.csv','wb') as testfile:
    csv_writer=csv.writer(testfile)

collection = ['hey', '5', 'd']
for x in collection:
    csv_writer.writerow(x)

1 Answer 1

1

Indent your code block to be within the with statement scope, and wrap each string in a list to make it an actual row:

import csv
with open('onehot.csv','wb') as testfile:
    csv_writer=csv.writer(testfile)

    collection = ['hey', '5', 'd']
    for x in collection:
        csv_writer.writerow([x])

File objects are context managers, and the with statement informs them when the context is exited (the block under the with statement has ended or an exception was raised). File objects respond by closing the file, so you can't write to it anymore outside of a with block.

Sign up to request clarification or add additional context in comments.

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.