I'm using Box
Python API to write some tools. Therefore, one of them is to upload a file to Box
. They use a StringIO
as the object file.
I need to read a file locally and write its content to the StringIO
buffer, then pass that to the Box
API 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 the StringIO
buffer?
Perhaps the cleanest, most succinct solution to write a String to a File is through the use of the FileWriter. With this class, you pass its constructor the File object that you'd like to write to, and then you call its write method to write strings of data to the file.
The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.
StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.
Python has a built-in module named StringIO. It can produce file-like objects (also known as memory files or string buffer) and be read and written just like files. As the above example shown, we can use the write () method to write data to a StringIO object. The getvalue () method helps us get the entire content of a StringIO object.
Python StringIO. When you write a python program, you may not read and write data from/to files, you can also read and write data in memory ( for example, read/write data in String object). In this case, you can use the python module StringIO to achieve it.
StringIO gives us abilities of operating strings in memory, and it has a consistent interface with reading and writing files. Thanks for reading. Python is a very convenient tool to handle files.
Since a StringIO object is a file-like object, we can use the file handling operations to read it. A good habit is closing the StringIO object after using it. The StringIO.close () method will help us free the relative memory space. If we operate a closed memory file, a ValueError will be raised.
You should be able to supply an open file instead of as StringIO
instance. This should do:
stream = open('mylocal_file')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With