Handling Files

A file is a named location on a disk drive that is used to store data. Each file is identified by its filename. Python contains inbuilt functions for reading data from files, as well as creating and writing to files.

There are two types of files. Text files and binary files. By default Python reads and writes data in a text file.

Text File

A text file stores sequences of characters. Plain text files, HTML files, program source code.

Use these file modes when opening a file in text mode:

  • “r” opens a file for reading, error if the file does not exist
  • “a” opens a file for appending, creates the file if it does not exist
  • “w” opens a file for writing, creates the file if it does not exist
  • “r+” opens a file for both reading and writing

Binary

A binary file is stored in the same format as the computer’s memory (RAM). Any images such as jpeg, audio, or program executable files

Use these file modes when opening a file in binary mode:

  • “rb” opens a file for binary reading, error if the file does not exist
  • “ab” opens a file for binary appending, creates the file if it does not exist
  • “wb” opens a file for writing, creates the file if it does not exist
  • “rb+” opens a file for both reading and writing

 

Lesson Content
0% Complete 0/3 Steps