{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# StringIO \n", "\n", "The StringIO module implements an in-memory file like object. This object can then be used as input or output to most functions that would expect a standard file object.\n", "\n", "The best way to show this is by example:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import StringIO" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Arbitrary String\n", "message = 'This is just a normal string.'" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Use StringIO method to set as file object\n", "f = StringIO.StringIO(message)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we have an object *f* that we will be able to treat just like a file. For example:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.read()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also write to it:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f.write(' Second line written to file like object')" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Reset cursor just like you would a file\n", "f.seek(0)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'This is just a normal string. Second line written to file like object'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Read again\n", "f.read()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Great! Now you've seen how we can use StringIO to turn normal strings into in-memory file objects in our code. This kind of action has various use cases, especially in web scraping cases where you want to read some string you scraped as a file.\n", "\n", "For more info on StringIO check out the documentation:https://docs.python.org/2/library/stringio.html" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }