如何在python中将rackspace cloudfile读入字符串?
我想从rackspace解析日志文件。我在用电话。 我之前已将文件保存到磁盘,然后使用如何在python中将rackspace cloudfile读入字符串?,python,gzip,rackspace,Python,Gzip,Rackspace,我想从rackspace解析日志文件。我在用电话。 我之前已将文件保存到磁盘,然后使用gzip从磁盘读取。打开 现在我在heroku上,不能/不想将文件保存到磁盘,但要在内存中解压 但是,我无法将对象作为字符串或伪文件对象下载来处理它 有人有主意吗 logString = '' buffer = logfile.stream() while True: try: logString += buffer.next() except StopIteration:
gzip从磁盘读取。打开
现在我在heroku上,不能/不想将文件保存到磁盘,但要在内存中解压
但是,我无法将对象作为字符串或伪文件对象下载来处理它
有人有主意吗
logString = ''
buffer = logfile.stream()
while True:
try:
logString += buffer.next()
except StopIteration:
break
# logString is always empty here
# I'd like to have something that enables me to do this:
for line in zlib.decompress(logString):
# having each line of the log here
更新
我注意到,空字符串并不完全正确。这是一个循环,第一次出现时为空。下一次发生时,我确实有数据(看起来像是gzip),但我得到了以下zlib错误:
zlib.error: Error -3 while decompressing data: incorrect header check
更新II
正如建议的那样,我实现了cStringIO,得到了相同的结果:
buffer = logfile.stream()
output = cStringIO.StringIO()
while True:
try:
output.write(buffer.next())
except StopIteration:
break
print(output.getvalue())
更新III
这一点现在起作用了:
output = cStringIO.StringIO()
try:
for buffer in logfile.stream():
output.write(buffer)
except StopIteration:
break
这里至少没有撞车,但似乎没有实际的线路:
for line in gzip.GzipFile(fileobj=output).readlines():
# this is never reached
这里怎么办?是否有一些简单的方法可以将传入的数据视为普通字符串,从而知道我的方法是否正确?我发现,read()
也是一个选项,这导致了一个类似这样的简单解决方案:
io = cStringIO.StringIO(logfile.read())
for line in GzipFile(fileobj=io).readlines():
impression = LogParser._parseLine(line)
if impression is not None:
impressions.append(impression)
logfile.save()
确实有效,但是logfile.stream().next()
调用返回空字符串?要将python字符串转换为类似内存对象的文件,请使用StringIO
模块(或者它是优化的C companioncStringIO
)。@MartijnPieters:没有save()
方法,只有保存到\u文件名()
,是的。请看我的更新!我试过StringIO,但没有成功。