所以我想用python在redis中保存一些任意的數據。由於redis通過將它存儲爲字符串來支持這一點,我想我可以再次用python讀取日期並將其寫入文件。起初,這並沒有奏效,因爲我使用了open()的標準'r'和'w'模式。 Python確實說他們是平等的。文件I/O和二進制模式的含義
當我將它更改爲'rb'和'wb'後,它可以工作,但爲什麼非二進制讀取或寫入會以某種方式更改數據?無論如何,它的意義是什麼?
這是一些可以工作的代碼,但只是將文件模式更改爲非二進制文件並觀察testfile_read.zip更改。你需要的Redis不過,易與PIP安裝安裝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"
我明白現在,但是我的代碼會以非二進制模式生成不同的文件 – RG337
@prgmjunkie:是的,您通常需要這種行爲,除非您正在編寫特殊格式的文件。 –
我正在寫一個標準文件,但沒有文本文件。我知道我需要二進制文件,但我只是不知道爲什麼,現在我知道了! – RG337