{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Cheat Sheet\n", "\n", "Basic cheatsheet for Python mostly based on the book written by Al Sweigart, [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) under the [Creative Commons license](https://creativecommons.org/licenses/by-nc-sa/3.0/) and many other sources.\n", "\n", "## Read It\n", "\n", "- [Website](https://www.pythoncheatsheet.org)\n", "- [Github](https://github.com/wilfredinni/python-cheatsheet)\n", "- [PDF](https://github.com/wilfredinni/Python-cheatsheet/raw/master/python_cheat_sheet.pdf)\n", "- [Jupyter Notebook](https://mybinder.org/v2/gh/wilfredinni/python-cheatsheet/master?filepath=jupyter_notebooks)\n", "\n", "## Reading and Writing Files\n", "\n", "### The File Reading/Writing Process\n", "\n", "To read/write to a file in Python, you will want to use the `with`\n", "statement, which will close the file for you after you are done.\n", "\n", "### Opening and reading files with the open function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('C:\\\\Users\\\\your_home_folder\\\\hello.txt') as hello_file:\n", " hello_content = hello_file.read()\n", "\n", "hello_content" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, you can use the _readlines()_ method to get a list of string values from the file, one string for each line of text:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('sonnet29.txt') as sonnet_file:\n", " sonnet_file.readlines()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also iterate through the file line by line:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('sonnet29.txt') as sonnet_file:\n", " for line in sonnet_file: # note the new line character will be included in the line\n", " print(line, end='')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Writing to Files" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('bacon.txt', 'w') as bacon_file:\n", " bacon_file.write('Hello world!\\n')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('bacon.txt', 'a') as bacon_file:\n", " bacon_file.write('Bacon is not a vegetable.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('bacon.txt') as bacon_file:\n", " content = bacon_file.read()\n", "\n", "print(content)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Saving Variables with the shelve Module\n", "\n", "To save variables:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import shelve\n", "\n", "cats = ['Zophie', 'Pooka', 'Simon']\n", "with shelve.open('mydata') as shelf_file:\n", " shelf_file['cats'] = cats" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To open and read variables:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with shelve.open('mydata') as shelf_file:\n", " print(type(shelf_file))\n", " print(shelf_file['cats'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Just like dictionaries, shelf values have keys() and values() methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to the list() function to get them in list form." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with shelve.open('mydata') as shelf_file:\n", " print(list(shelf_file.keys()))\n", " print(list(shelf_file.values()))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Saving Variables with pprint.pformat" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pprint\n", "\n", "cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]\n", "pprint.pformat(cats)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('myCats.py', 'w') as file_obj:\n", " file_obj.write('cats = {}\\n'.format(pprint.pformat(cats)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reading ZIP Files" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import zipfile, os\n", "\n", "os.chdir('C:\\\\') # move to the folder with example.zip\n", "with zipfile.ZipFile('example.zip') as example_zip:\n", " print(example_zip.namelist())\n", " spam_info = example_zip.getinfo('spam.txt')\n", " print(spam_info.file_size)\n", " print(spam_info.compress_size)\n", " print('Compressed file is %sx smaller!' % (round(spam_info.file_size / spam_info.compress_size, 2)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Extracting from ZIP Files\n", "\n", "The extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the current working directory." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import zipfile, os\n", "\n", "os.chdir('C:\\\\') # move to the folder with example.zip\n", "\n", "with zipfile.ZipFile('example.zip') as example_zip:\n", " example_zip.extractall()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The extract() method for ZipFile objects will extract a single file from the ZIP file. Continue the interactive shell example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with zipfile.ZipFile('example.zip') as example_zip:\n", " print(example_zip.extract('spam.txt'))\n", " print(example_zip.extract('spam.txt', 'C:\\\\some\\\\new\\\\folders'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating and Adding to ZIP Files" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import zipfile\n", "\n", "with zipfile.ZipFile('new.zip', 'w') as new_zip:\n", " new_zip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This code will create a new ZIP file named new.zip that has the compressed contents of spam.txt." ] } ], "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.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }