Python File Handling

Python File Handling

File handling is an essential part of any web application or software project. Whether you need to process uploaded files, read configuration settings, log errors, or save user data, you must know how to interact with the file system.

Python has several built-in functions for creating, reading, updating, and deleting files.


The open() Function

The key function for working with files in Python is the open() function.

The open() function takes two primary parameters:

  1. filename: The name (and path) of the file you want to open.
  2. mode: A string specifying the mode in which the file is opened.

File Opening Modes

There are four different methods (modes) for opening a file:

Text vs. Binary

In addition to the operational mode, you can specify if the file should be handled as text or binary mode:


Basic Syntax

To open a file for reading, it is enough to specify the name of the file. By default, Python assumes "rt" (Read and Text).

Syntax Example

// This is the exact same as open("demofile.txt", "rt")
f = open("demofile.txt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them unless you want to be explicit for code readability.


Exercise

?

What is the default mode when you use the open() function without specifying a mode?