---
title: "将任何内存中的python对象简单保存到文件中以备恢复：shelve模块"
author: "wjm251"
date: "2010-07-30T17:03:51Z"
tags: []
categories: ["编程语言"]
slug: "python-shelve"
draft: false
lastmod: "2010-08-06T11:06:44Z"
id: 725650
url: "https://appofis.iteye.com/blog/725650"
---

```python
#coding=cp936                      
temppath = u"D:\\你好新建文件夹\\a"
import shelve                      
cache = shelve.open(temppath, 'c') 
cache["hi"] = "ss"                 
cache.close()
```


这是个简单的方法，shelve.open的模式'c'
 表示没有就创建示
cache有着和dict一样的接口，非常好用。

项目中使用（Windows XP系统）发现传入的文件路径如果有中文，必须是utf-8编码的str对象才可以， gbk的str和unicode对象
都不行，感觉不正常，给官网提了个issue，果然有答复补丁。
http://bugs.python.org/issue9393
但我们自己只能用utf-8暂时规避了