Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Data Science Basics Exporting Exporting CSV Files

Do we need to close the file after finishing it for this video?

Do we need to close the file after finishing it for this video? I saw python doc saying that it's nescessary to close the file when we finish it to free up the resource taken by the open file.

Kat Chuang
Kat Chuang
Treehouse Guest Teacher

Hi @chokdeesrisuk, I usually close the file. I like to think of it like tying shoelaces tightly before running - you don't have to but it's better to avoid the risks :)

1 Answer

Good point!

The following should work instead (and remove the extra line breaks in the resulting csv):

def write_to_file(filename, data_sample):
    with open(filename, 'w', encoding='utf-8', newline='') as csvfile:
        example = csv.writer(csvfile, dialect='excel')
        example.writerows(data_sample)

The with open(...) as csvfile is straight from the Python documentation for csv.writer