Reading from a file and writing to StringIO - Python

I am using the Python Box API to write some tools. Therefore, one of them is to upload the file to Box . They use StringIO as an object file. I need to read the file locally and write its contents to the StringIO buffer, and then pass this to the API Box , as shown in the code below:

 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) 

Simple enough, how can I read from a local file and then write to StringIO buffer?

+5
source share
1 answer

You should be able to provide an open file instead of an instance of StringIO . This should do:

 stream = open('mylocal_file') 
+3
source

Source: https://habr.com/ru/post/1238196/


All Articles