INF1-IP: Week 6

Lecture 10 - I/O 1: Reading and writing files

 

Learning outcomes
  • Using escape sequences to include newlines, tabs, backslashes, and quotes in strings
  • Distinguishing relative and absolute file paths, and writing paths that work on Windows, Linux, and macOS
  • Opening and closing text files with open() and .close(), and more safely with with open(...)
  • Reading a whole file or processing it one line at a time
  • Writing, appending, and choosing which whitespace to remove

 

Key terms
Click to expand.

Escape sequence

A backslash followed by a character that represents something such as a newline or a quote in a string.

Path

A location in a filesystem.

Absolute path

A path starting from the root of a filesystem.

Relative path

A path starting from a particular folder.

Path separator

The character between folder names in a path: / on Linux and macOS, \ on Windows.

Working directory

The directory from which relative paths are interpreted.

File object

An object through which a program reads or writes a file, also called a file handle.

Text encoding

A rule for representing characters as bytes. UTF-8 is a widely used encoding for Unicode text.

 

New syntax
Click to expand.

\n, \t, \\, \" and \'

Escape sequences for a newline, a tab, a backslash, a double quote, and a single quote.

repr(value)

Returns a representation of value. For strings this shows quotes and escape sequences.

file = open(path, mode, encoding="utf-8") and file.close()

Opens a text file and returns a file object; closing it saves any text still waiting to be written. Less safe than using with.

with open(path, mode, encoding="utf-8") as file:

Opens a text file for the indented block, then closes it.

"r", "w", "a"

File modes for reading, replacing contents, and appending, respectively.

file.read()

Returns the remaining contents of an open text file as a string.

file.write(text)

Writes a string without adding a newline. Returns the number of characters written.

file.closed

Returns True or False depending on whether the file is closed or not.

for line in file:

Reads an open text file one line at a time.

text.rstrip("\n")

Returns the text with newline characters removed from its right-hand end.

FileNotFoundError

A type of error raised when a requested file or directory cannot be found.

 

Further practice

 


 

Lecture 11 - Modules

 

Learning outcomes
  • Importing modules and choosing an import style
  • Using dir() and help() to explore unfamiliar tools
  • Constructing and inspecting file paths with pathlib
  • Grouping related functions into modules
  • Using main() and __name__ to separate reusable definitions from a demonstration

 

Key terms
Click to expand.

Module

A named unit of Python code containing definitions and statements.

Standard library

The modules supplied with Python.

Namespace

A collection of names and the objects they refer to.

Alias

An alternative name for an object; for example given to imported modules with long names.

Separation of concerns

Giving different responsibilities to different functions or modules in your code.

Main guard

A condition that runs a block when a file is executed directly, while skipping it when the file is imported.

 

New syntax
Click to expand.

import module

Makes a module available through its name.

from module import name

Makes a selected name from a module available directly.

import module as alias

Imports a module under an alternative name.

dir(module)

Returns a list of names available in a module.

Path("directory") / "file.txt"

Constructs a path by joining components, after importing Path from pathlib.

Path.cwd(), path.resolve(), path.is_absolute()

Finds the working directory, forms an absolute path, and checks whether a path is absolute.

path.name, path.suffix, path.parent

Inspects the last component, extension, and containing directory of a path.

path.mkdir(exist_ok=True)

Creates a directory, without throwing an error if it already exists.

__name__

The module's name, or "__main__" when Python executes a file directly.

if __name__ == "__main__":

Begins a main guard. Its indented body conventionally calls a function named main().

 

Further practice

 


 

Tutorial

Tutorial 4: Object Permanence has you practice reading, processing, and writing data from and to files, in preparation for Assignment 2.

  • Interactive notebook (right-click → Save As... then remove the .txt part so it is saved as an .ipynb)
    • Note that this notebook was created to be used in Notable; its interactive checker cells might not work in every environment.
  • You'll also need nessiesightings.csv and, for the first bonus task, moragsightings.csv

 


 

Assessment

No assessment this week.

 


 

License
All rights reserved The University of Edinburgh