Python for AI: A Crash Course

Nov 16 2024 · Python 3.12, JupyterLab 4.2.4

Lesson 04: Working with Local Data (File Operations & Data Handling)

File Handling Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Demo

In this demo, you’ll write code to read and write text files. Or, more accurately, you’ll write code that writes a text file and then write code that reads that file.

Writing To a Text File

Start by writing a text file to your computer’s filesystem. That way, you’ll have a text file you can read for the file-reading part of this exercise.

Writing To a Text File the Old Way

The old way of writing text files in Python—which happens to be the current way of writing text files in most other programming languages—is to open a file, write to that file, and then close it. Do that now using the open() function and file.close() method.

file = open("programming-languages.txt", "w")
file.write("Programming Languages")
file.write("=====================")
file.close()
Programming Languages=====================
file = open("programming-languages.txt", "w")
file.write("Programming Languages\n")
file.write("=====================\n")
file.close()
Programming Languages
=====================

Writing To a Text File the Preferred Way

In the preferred way, you perform file operations inside a with block, perform setup operations at the start of the block and clean up operations once the block has completed executing. In the case of files, with automatically closes the file at the end of the block.

with open("programming-languages.txt", "w") as file:
  file.write("Programming Languages\n")
  file.write("=====================\n")

  for language in programming_languages:
    line = (
      f"{language["name"]} was created by {language["creator"]} " +
      f"and first appeared in {language["year_appeared"]}.\n"
    )
    file.write(line)
Programming Languages
=====================
Python was created by Guido van Rossum and first appeared in 1991.
Miranda was created by David Turner and first appeared in 1985.
Ruby was created by Yukihiro Matsumoto and first appeared in 1995.
Rebol was created by Carl Sassenrath and first appeared in 1997.
Swift was created by Chris Lattner and first appeared in 2014.
ActionScript was created by Gary Grossman and first appeared in 1998.
Kotlin was created by JetBrains and first appeared in 2011.
CoffeeScript was created by Jeremy Ashkenas and first appeared in 2009.

Appending To a Text File

Now, add to programming-languages.txt without overwriting any existing content. You can do this by writing to it in "a" (append) mode.

old_school_languages = [
  "ALGOL\n"
  "BASIC\n",
  "COBOL\n",
  "FORTRAN\n",
  "Lisp\n"
]

with open("programming-languages.txt", "a") as file:
  file.write("Let's not forget the old guard:\n")
  file.writelines(old_school_languages)
Programming Languages
=====================
Python was created by Guido van Rossum and first appeared in 1991.
Miranda was created by David Turner and first appeared in 1985.
Ruby was created by Yukihiro Matsumoto and first appeared in 1995.
Rebol was created by Carl Sassenrath and first appeared in 1997.
Swift was created by Chris Lattner and first appeared in 2014.
ActionScript was created by Gary Grossman and first appeared in 1998.
Kotlin was created by JetBrains and first appeared in 2011.
CoffeeScript was created by Jeremy Ashkenas and first appeared in 2009.
Let's not forget the old guard:
ALGOL
BASIC
COBOL
FORTRAN
Lisp

ALGOLBASICCOBOLFORTRANLisp

Reading From a Text File

You started this exercise by writing a text file so you’d have one to read. Not, it’s time to read it!

with open("programming-languages.txt", "r") as file:
  data = file.read()
print(data)
Programming Languages
=====================
Python was created by Guido van Rossum and first appeared in 1991.
Miranda was created by David Turner and first appeared in 1985.
Ruby was created by Yukihiro Matsumoto and first appeared in 1995.
Rebol was created by Carl Sassenrath and first appeared in 1997.
Swift was created by Chris Lattner and first appeared in 2014.
ActionScript was created by Gary Grossman and first appeared in 1998.
Kotlin was created by JetBrains and first appeared in 2011.
CoffeeScript was created by Jeremy Ashkenas and first appeared in 2009.
Let's not forget the old guard:
ALGOL
BASIC
COBOL
FORTRAN
Lisp

with open("programming-languages.txt", "r") as file:
  data = file.readlines()
print(data)
with open("programming-languages.txt", "r") as file:
  for line in file:
    print(line)
Programming Languages

=====================

Python was created by Guido van Rossum and first appeared in 1991.

Miranda was created by David Turner and first appeared in 1985.

Ruby was created by Yukihiro Matsumoto and first appeared in 1995.

Rebol was created by Carl Sassenrath and first appeared in 1997.

Swift was created by Chris Lattner and first appeared in 2014.

ActionScript was created by Gary Grossman and first appeared in 1998.

Kotlin was created by JetBrains and first appeared in 2011.

CoffeeScript was created by Jeremy Ashkenas and first appeared in 2009.

Let's not forget the old guard:

ALGOL

BASIC

COBOL

FORTRAN

Lisp
with open("programming-languages.txt", "r") as file:
  for line in file:
    print(line.rstrip())

Handling Exceptions

For the sake of simplicity, the previous examples in this exercise have ignored exception handling. It’s generally a good idea to incorporate it into file-handling code.

try:
  with open("does-not-exist.txt", "r") as file:
    data = file.read()
except FileNotFoundError as e:
  print(f"File not found! Details:\n{e}")
except OSError as e:
  print(f"I/O error (probably)! Details:\n{e}")
except Exception as e:
  print("An unexpected error occurred! Call the developer.")
  print(f"Details:\n{e}")
File not found! Details:
[Errno 2] No such file or directory: 'does-not-exist.txt'
import random

try:
  with open("programming-languages.txt", "r") as file:
    if random.randint(1, 3) == 1:
      raise OSError("Disk error")
    print(file.read())
except FileNotFoundError as e:
  print(f"File not found! Details:\n{e}")
except OSError as e:
  print(f"I/O error (probably)! Details:\n{e}")
except Exception as e:
  print("An unexpected error occurred! Call the developer.")
  print(f"Details:\n{e}")
else:
  print("Congratulations! No errors!")
finally:
  print("All done.")
See forum comments
Cinema mode Download course materials from Github
Previous: File Handling Next: CVS Files