Sign InCoursewareNuggetsTutorials CoursesCodePad

Files and File Path

When your program ends, all the variable contents are gone. If you want to keep your data around, you need to save it to a file. A file has two key properties:

  • filename – the name of a file. The part of the filename after the last period is called the file’s extension, which tells you the file’s type. For example, file space.png is an image file with extension .png.
  • path – the location of a file. For example, /pygame/img/ is a path in which pygame and img are folders (directories).

Text vs. Binary Files

In Python, a file is categorized as either text or binary, and the difference between the two file types is important.

A text file is structured as a sequence of lines. Each line includes a sequence of characters with a special character at the end, called the End of Line (EOL) character, which terminates the current line. A binary file is any type of file – an image file, for example – that is not a text file. Because of its special nature, a binary file can only be processed by an application that understands the file’s structure.

Absolute vs. Relative Paths

There are two ways to specify a file path. An absolute path always begins with the root folder. A relative path is relative to the program’s current working directory.

Every program that runs on your computer has a current working directory (cwd). Any filename or path that does not begin with the root folder is assumed to be under the current working directory.

The dot (.) and dot-dot (..) folders are not real folders but special names that can be used in a path. A single period (.) for a folder name is a shorthand for “this directory.” Two periods (..) means “the parent folder.”

© CS Wonders·About·Gallery·Fun Facts·Cheatsheet