File Handling
Definition: File handling is an important part of any web or desktop application. It allows a Python program to open, read, write, create, and delete files stored on the computer's hard drive.
Why: Variables inside a program disappear as soon as the code stops running. File handling is a key practical topic because it allows you to permanently save data (like logs, configurations, or user records) so it can be accessed again later.
The with Statement (Recommended Practice)
In Python, it is best practice to use the with statement when working with files. It ensures that the file is properly and safely closed after the operations are finished, even if an error occurs during execution.
1. Writing to a File
To write data to a file, you open it using the "w" (write) mode. If the file does not exist, Python will automatically create it. If it already exists, the existing content will be completely overwritten.
Example
with open("sample.txt", "w") as file:
file.write("Welcome to Python programming")
2. Reading from a File
To extract data from a file, you open it using the "r" (read) mode. You can then use the .read() method to pull the contents into a variable.
Example
with open("sample.txt", "r") as file:
content = file.read()
print(content)
Explanation of Core Components
open()Function: This built-in function takes two main parameters: the name of the file you want to target and the mode you want to use."w"Mode: Short for write. It positions the pointer at the beginning of the file and prepares it for outputting data."r"Mode: Short for read. It positions the pointer at the beginning of the file to fetch data. If the specified file does not exist, Python will raise aFileNotFoundError.with ... as file:: This acts as a context manager. It handles file clean-up automatically so you don't have to manually writefile.close()every time.
Key Notes
- Appending to a File: If you want to add data to an existing file without wiping out its old contents, use the
"a"(append) mode instead of"w". - Reading Line by Line: For large files, instead of using
.read()(which loads the entire file into memory), you can use aforloop to process the file line by line:with open("sample.txt", "r") as file: for line in file: print(line.strip())
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute