5
我正在使用Box
Python API來編寫一些工具。因此,其中之一是將文件上傳到Box
。他們使用StringIO
作爲目標文件。 我需要在本地讀取文件和寫入其內容的StringIO
緩衝區,然後傳遞到Box
API如下圖所示的代碼:從文件讀取並寫入到StringIO - Python
def upload_file(self, filename, folder_id='0'):
assert self.client is not None
try:
stream = StringIO.StringIO()
# replace this line a file read
stream.write('Box Python SDK Test!')
stream.seek(0)
box_file = self.client.folder(folder_id=folder_id).upload_stream(
stream, filename,
preflight_check=True)
return box_file.name
except BoxAPIException, e:
self.log.exception(e)
夠簡單了,我怎麼可以從本地文件讀取,然後寫入StringIO
緩衝區?
如果你真的需要一個StringIO(可能文件對象會這樣做),只要做'stream.write(open(filename).read())'。 – tdelaney