- くだすれPython(超初心者用) その25©2ch.net
780 :デフォルトの名無しさん[sage]:2015/03/21(土) 00:15:32.82 ID:pulqrllr - >>770
>ファイルの入出力の時文字列型になってしまうのはどうしても避けられないんでしょうか? バイナリとかもあるけど、基本的にはそう。 PythonのオブジェクトがPythonのオブジェクトでいられるのはPythonの中だけ JSON云々はその次の話だけど、それでもhttp://docs.python.jp/3.4/library/json.html#py-to-json-tableにある以外の型が渡された場合はTypeErrorがraiseされる。 json.dump()にdefault引数を指定すること上記のテーブルにある以外のオブジェクトが渡されたときに呼ばれる関数を指定できる。 http://docs.python.jp/3.4/library/json.html#json.dump >>> from datetime import time, date, datetime >>> import json >>> with open("test", "w") as fp: json.dump({"勉強したセクション": datetime(2015, 3, 10, hour=13, minute=15)}, fp, default=str) >>> with open("test", "r") as fp: print(json.load(fp)) {'勉強したセクション': '2015-03-10 13:15:00'}
|