Coding 101

May 8th 2014

Coding 101 16

Python - The External Data Circle of Life

Today we're going to show you how to output to a file, and we're getting back into lists.

Although the show is no longer in production, you can enjoy episodes from the TWiT Archives.
Guests: Dale Chase
Category: Help & How To

Welcome to Coding 101 - It's the TWiT show that gives YOU the knowledge to live in the wonderful world of the programmer. This week we are introducing our newest module, Python with Code Warrior Dale Chase!

To see all the code used in today's episode, go to Our Github Repository for Module 2

Ivory Tower: External File IO

Using external data reqires knowledge of four functions: "open()", " read()", "write()" and "close()"

open()

This function opens a file with the flags and mode of your choosing. For simplicity, we're only using the "r" "w" modes.

  • The "r" mode opens a file for "read only" use
  • The "w" mode blanks the file prepares to write to the file

* Note that this function DOES NOT READ THE FILE INTO A VARIABLE.

USAGE:

text_file = open("/Users/PadreSJ/Desktop/C101-16/write.txt", "r")

  • This opens a file called "write.txt" in READ-ONLY mode and sets the pointer in variable "text_file"

text_file = open("/Users/PadreSJ/Desktop/C101-16/write.txt", "w")

  • This opens a file called "write.txt" in WRITE MODE, sets the pointer in variable "text_file" and blanks that file.

read()

This function reads the contents of the file into a string variable.

USAGE:

textFromFile = text_file.read()

  • This reads the file at pointer "text_file" into the string variable "textFromFile"

write()

This function writes a string into an external file.

USAGE:

text_file.write(MyString)

  • This writes the contents of the string variable "MyString" into the file indexed at "text_file"

close()

This function closes access to the file. USAGE: text_file.close() #This closes the file indexed at "text_file"

Get in Touch With Us!

Bandwidth for Coding 101 is provided by CacheFly.