deseosuho
deseosuho

Reputation: 1038

python write and open temporary csv

Using Python 3 on a windows machine:

I have a function to take a list of lists and open it as a csv file using my default application (excel). Despite closing the file after writing, I get a 'locked for editing' message when excel starts.

def opencsv(data):
        """saves a list of lists as a csv and opens"""
        import tempfile
        import os
        import csv
        handle, fn = tempfile.mkstemp(suffix='.csv')
        with open(fn,"w", encoding='utf8',errors='surrogateescape',\
                      newline='') as f:
            writer=csv.writer(f)
            for row in data:
                try:
                    writer.writerow(row)
                except Exception as e:
                    print ('Error in writing row:',e)
            f.close()

        url = 'file://' + fn.replace(os.path.sep, '/')
        os.startfile(fn)
opencsv([['d1','d2'],['d3','d4','d5']])

error window

How can I fix this?

Upvotes: 1

Views: 7362

Answers (1)

deseosuho
deseosuho

Reputation: 1038

Answer from swstephe's input:

The issue is that mkstemp opens the file and associates it with an os handle. In my original code I was not closing this file properly. See below for updated code.

def opencsv(data):
    """saves a list of lists as a csv and opens"""
    import tempfile
    import os
    import csv
    handle, fn = tempfile.mkstemp(suffix='.csv')
    with os.fdopen(handle,"w", encoding='utf8',errors='surrogateescape',\
                  newline='') as f:
        writer=csv.writer(f)
        for row in data:
            try:
                writer.writerow(row)
            except Exception as e:
                print ('Error in writing row:',e)

    print (fn)
    os.startfile(fn)

Upvotes: 2

Related Questions