python 写入并打开临时 csv

python write and open temporary csv

在 windows 机器上使用 Python 3:

我有一个功能可以获取列表列表并使用我的默认应用程序 (excel) 将其作为 csv 文件打开。尽管写入后关闭文件,但在 excel 启动时我收到一条 'locked for editing' 消息。

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']])

我该如何解决这个问题?

来自 swstephe 输入的答案:

问题是 mkstemp 打开文件并将其与 os 句柄相关联。在我的原始代码中,我没有正确地 closing 这个文件。请参阅下面的更新代码。

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)