2014-04-29 21 views
0

我想寫一個cStringIO緩衝區到磁盤。緩衝區可能代表pdf,圖像或html文件。從cStringIO寫文件

我採取的方法似乎有點不可靠,所以我也開放其他方法作爲解決方案。

def copyfile(self, destfilepath): 
    if self.datastream.tell() == 0: 
     raise Exception("Exception: Attempt to copy empty buffer.") 
    with open(destfilepath, 'wb') as fp: 
     shutil.copyfileobj(self.datastream, fp) 
    self.__datastream__.close() 

@property 
def datastream(self): 
    return self.__datastream__ 

#... inside func that sets __datastream__ 
while True: 
    buffer = response.read(block_sz) 
    self.__datastream__.write(buffer) 
    if not buffer: 
     break 
# ... etc .. 

test = Downloader() 
ok = test.getfile(test_url) 
if ok: 
    test.copyfile(save_path) 

我採取這種做法,因爲我不想要開始書面方式數據到磁盤,直到我知道我已經成功地讀取整個文件,這是一個類型的,我感興趣的

調用的CopyFile後()磁盤上的文件始終爲零字節。

回答

0

哎呦!

我在嘗試讀取它之前忘記重置流的位置;所以它從最後讀取,因此零字節。將光標移到開頭可以解決問題。

def copyfile(self, destfilepath): 
    if self.datastream.tell() == 0: 
     raise Exception("Exception: Attempt to copy empty buffer.") 
    self.__datastream__.seek(0) # <-- RESET POSITION TO BEGINNING 
    with open(destfilepath, 'wb') as fp: 
     shutil.copyfileobj(self.datastream, fp) 
    self.__datastream__.close()