See More

{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Quick recap\n", "- reading and writing from files" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# read from file\n", "with open(\"data/mydata.txt\") as f:\n", " for line in f:\n", " print(line.strip())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# write to file\n", "with open( \"out.txt\", \"w\" ) as out:\n", " out.write(\"hello\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Session 2.4\n", "- Delimited files" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# example in data/mydata.txt (tab delimited)\n", "# read into a dictionary (more convenient structure)\n", "results = []\n", "with open('data/mydata.txt') as f:\n", " header = f.readline()\n", " for line in f:\n", " idx, org, score = line.split()\n", " #print(idx, org, score)\n", " row = {'index': int(idx), 'organism': org, 'score': float(score)}\n", " #print(row)\n", " results.append(row)\n", "print(results)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# write results into a comma separated file\n", "with open('mydata.csv', 'w') as out:\n", " out.write('index,organism,score\\n')\n", " for r in results:\n", " out.write('{},{},{}\\n'.format(r['index'], r['organism'], r['score']))\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }