2017-02-23 2 views
0

データフレームを常に更新し、ディスクに保存するスクリプトがあります(古いcsvファイルを上書きします)。私は、保存コールでプログラムを中断すると、df.to_csv("df.csv")、すべてのデータが破棄され、df.csvは空で、column-indexしか含まれていないことが分かりました。パンダto_csv上書き、データ損失を防ぐ

一時的にデータをdf.temp.csvに保存してから、df.csvを置き換えて回避策を実行できます。しかし、貯蓄 "Atomary"を作り、データの損失を防ぐためには、pythonの、短い方法がありますか?これは、セービングコール時に割り込みが発生したときに得られるスタックトレースです。

Traceback (most recent call last): 
    File "/opt/homebrew-cask/Caskroom/pycharm/2016.1.3/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1531, in <module> 
    globals = debugger.run(setup['file'], None, None, is_module) 
    File "/opt/homebrew-cask/Caskroom/pycharm/2016.1.3/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 938, in run 
    pydev_imports.execfile(file, globals, locals) # execute the script 
    File "/Users/user/test.py", line 49, in <module> 
    d.to_csv("out.csv", index=False) 
    File "/usr/local/lib/python2.7/site-packages/pandas/core/frame.py", line 1344, in to_csv 
    formatter.save() 
    File "/usr/local/lib/python2.7/site-packages/pandas/formats/format.py", line 1551, in save 
    self._save() 
    File "/usr/local/lib/python2.7/site-packages/pandas/formats/format.py", line 1652, in _save 
    self._save_chunk(start_i, end_i) 
    File "/usr/local/lib/python2.7/site-packages/pandas/formats/format.py", line 1666, in _save_chunk 
    quoting=self.quoting) 
    File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 1443, in to_native_types 
    return formatter.get_result_as_array() 
    File "/usr/local/lib/python2.7/site-packages/pandas/formats/format.py", line 2171, in get_result_as_array 
    formatted_values = format_values_with(float_format) 
    File "/usr/local/lib/python2.7/site-packages/pandas/formats/format.py", line 2157, in format_values_with 
    for val in values.ravel()[imask]]) 
    File "/usr/local/lib/python2.7/site-packages/pandas/formats/format.py", line 2108, in base_formatter 
    return str(v) if notnull(v) else self.na_rep 
    File "/usr/local/lib/python2.7/site-packages/pandas/core/common.py", line 250, in notnull 
    res = isnull(obj) 
    File "/usr/local/lib/python2.7/site-packages/pandas/core/common.py", line 73, in isnull 
    def isnull(obj): 
    File "_pydevd_bundle/pydevd_cython.pyx", line 937, in _pydevd_bundle.pydevd_cython.ThreadTracer.__call__ (_pydevd_bundle/pydevd_cython.c:15522) 
    File "/opt/homebrew-cask/Caskroom/pycharm/2016.1.3/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_is_thread_alive.py", line 14, in is_thread_alive 
    def is_thread_alive(t): 
KeyboardInterrupt 
+0

おそらく、 'd.to_csv(" out.csv "、index = False、mode = 'a')'のように古いものに結果を追加することができます。これにより、それらが上書きされないようにします。 –

+0

それからデータが複製されます...私はセービングコールでそれを中断すればどうなりますか?おそらく損失はありませんが、私も問題があると思います... – user1506145

答えて

1

あなたのアトミック上書きを処理するために、コンテキストマネージャを作成することができます。

import os 
import contextlib 

@contextlib.contextmanager 
def atomic_overwrite(filename): 
    temp = filename + '~' 
    with open(temp, "w") as f: 
     yield f 
    os.rename(temp, filename) # this will only happen if no exception was raised 

パンダDataFrameto_csv方法は受け付けますファイルオブジェクトをパスの代わりに使用することができます。

with atomic_overwrite("df.csv") as f: 
    df.to_csv(f) 

私が選択した一時ファイル名は、最後にチルダが付いた要求されたファイル名です。必要に応じて、他のコードを使用するようにコードを変更することはもちろん可能です。また、ファイルを開くモードを正確にはわからないので、の代わりに"w"が必要な場合があります。

1

あなたができる最善のは、最後の書き込み操作が完了するまでプログラムを終了して待機シグナルハンドラ(signalモジュール)を実装することです。線に沿って

サムシング(擬似コード):

import signal 
import sys 
import time 
import pandas as pd 

lock = threading.Lock() 

def handler(signum, frame): 
    # ensure that latest data is written 
    sys.exit(1) 

signal.signal(signal.SIGTERM, handler) 
signal.signal(signal.SIGINT, handler) 

while True: 
    # might exit any time. 
    pd.to_csv(...) 
    time.sleep(1) 
関連する問題