【问题标题】:python write and open temporary csvpython写入并打开临时csv
【发布时间】:2015-10-14 14:54:38
【问题描述】:

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

我该如何解决这个问题?

【问题讨论】:

  • 如果您使用with open(fn) .. 构造,您实际上根本不需要关闭文件。不过,不要认为这会解决问题。
  • 进程结束后还能打开同一个文件吗?
  • mkstemp 创建文件并在一个元组中返回文件描述符:“mkstemp() 返回一个元组,其中包含一个打开文件的 OS 级句柄(由 os.open() 返回)以及该文件的绝对路径名,按此顺序。”您无需再次打开它,只需“csv.writer(handle)”即可。这意味着您将无法声明大多数开放选项。
  • 您创建了 'url' 但不使用它。也许你想要 os.startfile(url)
  • @swstephe:听起来像是对我的回答。 handle 仍然开放。

标签: python csv temporary-files


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2017-10-09
    • 2017-07-28
    • 1970-01-01
    相关资源
    最近更新 更多