【发布时间】:2014-07-06 03:55:15
【问题描述】:
所以我想用python在redis中保存一些任意数据。由于redis通过将其存储为字符串来支持这一点,我认为我可以再次使用python读取日期并将其写入文件。起初这不起作用,因为我使用了 open() 的标准 'r' 和 'w' 模式。 Python确实说它们是平等的。
在我将其更改为“rb”和“wb”后,它可以工作,但为什么非二进制读取或写入会以某种方式更改数据?到底有什么意义呢?
这里有一些有效的代码,但只需将文件模式更改为非二进制并观察 testfile_read.zip 的变化。不过你确实需要 redis,使用 pip install redis 很容易安装
import redis
import os.path
version=1.0
path='testfile.zip'
r_server=redis.Redis("127.0.0.1")
fp = open(path,'rb')
test=fp.read()
fp.close()
r_server.hset('testfile',version,test)
r_server.hset('testfile','currver',version)
test2=r_server.hget('testfile',version)
if test==test2:
print "read from file and read from redis are the same"
else:
print "read from file and read from redis are the NOT!! same"
fp2 = open("testfile_read.zip",'wb')
fp2.write(test2)
fp2.close()
fp3 = open("testfile_read.zip",'rb')
test3=fp3.read()
fp3.close()
if test2==test3:
print "redis is equal to written file"
else:
print "redis is NOT!!! equal to written file"
【问题讨论】: