Keyadun
Keyadun

Reputation: 915

CSV NamedTemporaryFile not saving properly

I'm trying to make a csv file using Python's csv and tempfile tools. I've been declaring it as follows:

csvattachment = tempfile.NamedTemporaryFile(suffix='.csv', prefix=('student_' + studentID), delete=False)
with open(csvattachment.name, 'w+') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=',')
    filewriter.writerow([ #WRITE CONTENT HERE])

What I am then doing after is attaching this file and sending it out. The problem with that is that instead of being called 'student_1736823.csv' the attachment name is something uglier like <tempfile._TemporaryFileWrapper object at 0x10cbf5e48>

Upvotes: 1

Views: 2682

Answers (1)

nosklo
nosklo

Reputation: 223172

The NamedTemporaryFile() class already returns an open file, you don't have to reopen it

with tempfile.NamedTemporaryFile(suffix='.csv', prefix=('student_' + studentID),
        delete=False, mode='w+') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=',')
    filewriter.writerow([ #WRITE CONTENT HERE])

Upvotes: 3

Related Questions