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.
open() FunctionThe key function for working with files in Python is the open() function.
The open() function takes two primary parameters:
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading. It will return an error if the file does not exist."a" - Append - Opens a file for appending. It will create the file if it does not exist, and add new data to the end of the file."w" - Write - Opens a file for writing. It will overwrite any existing content, and create the file if it does not exist."x" - Create - Creates the specified file. It returns an error if the file already exists.In addition to the operational mode, you can specify if the file should be handled as text or binary mode:
"t" - Text - Default value. Used for standard text files (e.g., .txt, .csv)."b" - Binary - Used for binary mode (e.g., images like .jpg or .png, audio, or compiled data).To open a file for reading, it is enough to specify the name of the file. By default, Python assumes "rt" (Read and Text).
// 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.
What is the default mode when you use the open() function without specifying a mode?