【问题标题】:How do I force Python to append to a csv file that someone currently has open?如何强制 Python 附加到某人当前打开的 csv 文件?
【发布时间】:2019-07-29 12:44:06
【问题描述】:

有没有办法做到这一点?这是我当前的代码。

try:
    if len(df) > 0:
        with open(r'\\path\to\dir\IDS_' + str(now)[:-2] + '.csv', 'a') as f:
            df.to_csv(f, sep=',', header=False, index=True, encoding='utf-8')
            f.close()
except Exception, e:
    print e

【问题讨论】:

  • 你不需要f.close(),这就是with 语句的用途。
  • 如果有人在使用它,我认为您不能在文件中追加。您可以复制并附加到副本。
  • 您使用的是什么操作系统?你遇到了什么错误?请给出重现问题的步骤
  • 只是伪代码吗?似乎可行。如果您遇到任何问题,请尝试并更新帖子
  • @NickTheInventor 不,如果您使用with 语句,它将始终关闭文档。这就是在这里使用with 语句的全部意义如果您认真地看到这种行为,您应该尽快提交错误报告

标签: python pandas python-2.7 csv


【解决方案1】:

我发现我无法编辑某人已经打开的文件。我可以做的是通过使用 cPickle 将新信息转储到 pickle 文件中来处理 Exceptione,并在下次将文件放入 csv 时加载它。

try:
    if len(df) > 0:
        with open(r'\\path\to\dir\IDS_' + str(now)[:-2] + '.csv', 'a') as f:
            df.to_csv(f, sep=',', header=False, index=True, encoding='utf-8')
            f.close()
except Exception, e:
   cPickle.dump(df, open(r'C:\missed rows.p','wb'))

missed_rows = cPickle.load(open(r'C:\missed rows.p','rb'))

if len(missed_rows) > 0:
    df = missed_rows.append(df, sort=True)
    missed_rows = pd.DataFrame()
    cPickle.dump(missed_rows, open(r'C:\missed rows.p','wb'))
    df = df.drop_duplicates()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 2011-11-07
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多