Coding 205: Writing data to a file using Python

In this Learning Lab, you will learn how to write data to a file.

Objective

Completion Time: 15 minutes

  • Understand how to write data to a file
  • Understand how to append data to a file

Prerequisites

Python

  • To run the code samples, you need to have Python 3 installed on your machine.
  • If you are working on a DevNet Learning Lab PC at a DevNet event, Python 3.4.2 is already installed.
  • See How to Set up Your Own Computer section above for how to install Python on your own machine.

Python Requests Library

  • The code sample in Step 5 uses the Python Requests Library to simplify making REST API calls.
  • If you are working on a DevNet Learning Lab PC at a DevNet event, the Requests Library is already installed.
  • See How to Set up Your Own Computer section above for how to install the Requests Library on your own machine.

Clone Git Repo

  • If you are working on a DevNet Learning Lab PC at a DevNet event
    • Open the Git Command window by clicking on the Git CMD icon on the Task Bar or click on the Start button, then in the Run bar type: git cmd and press the Enter key.
  • If you are working from your own workstation, on your desktop open a command terminal.
  • Go to the root directory by typing: cd \
  • Create a directory called 'C:\DevNetCode\yourname' by typing: mkdir DevNetCode\<your-name>
    • For example: mkdir DevNetCode\brTiller
  • Go to the new directory by typing: cd \DevNetCode\<your-name>
    • For example: cd \DevNetCode\brTiller
  • Clone the coding skills sample code from GitHub. Enter the command below.
git clone https://github.com/CiscoDevNet/coding-skills-sample-code



Inside the directory you created you should now see directory 'coding-skills-sample-code'.



Step 1. Introduction

When writing applications, you often need to save some information to a text file.

Python makes this operation really easy.

Here's a simple example that creates a file named my-new-file.txt and writes the line "The grey penguin flies at noon." to the file.

# Use the open method to open a file
# Pass in the name of the file to open and mode. 'r' for read only 'w' if you want to write to the file
# To write to this file we will use "w"
# If the file does not exist, it will be created.
my_file_object = open("my-new-file.txt", "w")

my_file_object.write("The grey penguin flies at noon.")

my_file_object.close()

Fairly simple, right? Let's try it!