Python File Handling
File handling is an indispensable part of any programming language. Python provides simple yet powerful built-in functionality for creating, reading, and writing files.
Opening Files: open()
To operate on a file, you must first open it using the open() function. The open() function returns a file object.
Basic syntax:
file_object = open(file_name, mode)
file_name: The path to the file you want to open.mode: A string specifying how you intend to operate on the file.
File Modes (Mode)
Using with Statement
When handling files, best practice is to use the with statement. The with statement ensures that after the code block finishes execution, the file is properly closed even if an error occurs.
Reading Files
There are several methods for reading content from a file.
Suppose we have a file example.txt with the following content:
file.read()
Reads all contents of the file and returns them as a single string.
file.readline()
Reads only one line from the file at a time (including the newline character \n at the end) and returns it as a string.
file.readlines()
Reads all lines from the file and returns them as a list of strings. Each string in the list represents one line from the file.
Directly Iterating Over File Object
This is the most common and efficient way to read a file line by line, as it doesn't load all lines into memory at once.
Writing to Files
file.write(string)
Writes a string to the file. This method does not automatically add newline characters; you need to manually add \n.
file.writelines(list_of_strings)
Writes a list of strings to the file. Similarly, it does not automatically add newline characters.