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