python写和打开临时csv

时间:2015-10-14 14:54:38

标签: python csv temporary-files

在Windows机器上使用Python 3:

我有一个函数来获取列表列表并使用我的默认应用程序(excel)将其作为csv文件打开。尽管在写完之后关闭了文件,但是当excel启动时,我会收到“锁定编辑”消息。

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

回答swstephe的意见:

问题是mkstemp打开文件并将其与操作系统句柄相关联。在我的原始代码中,我没有正确关闭此文件。请参阅下面的更新代码。

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)