如何将文件对象保存到搁置文件?

时间:2016-05-12 22:31:34

标签: python file python-3.x object shelve

当我运行以下代码时:

import shelve

input = open("input.txt",)
shelveFile = shelve.open("myData")
shelveFile["inputFile"] = input
input.close()
shelveFile.close()

我希望搁置文件myData保存文件对象input。相反,运行代码会产生以下错误:

Traceback (most recent call last):
  File "/Users/ashutoshmishra/Documents/Sandbox/Sandbox3.py", line 5, in <module>
    shelveFile["inputFile"] = input
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/shelve.py", line 124, in __setitem__
    p.dump(value)
TypeError: cannot serialize '_io.TextIOWrapper' object

我想知道为什么我无法将文件对象input保存到搁置文件myData

1 个答案:

答案 0 :(得分:0)

以下答案取自@DanD。上述评论。

  

阅读文件:shelveFile["inputFile"] = input.read()