Introduction to Files
A file is a collection of data stored on a storage device. Files allow programs to store data permanently, unlike variables which store data temporarily in memory.
Types of Files
- Text Files: Store readable data (e.g.,
.txt,.csv) - Binary Files: Store non-readable data (e.g., images, videos)
Why File Handling is Important
- Store large data permanently
- Retrieve data when needed
- Share data between programs
- Useful in real-world applications like logs, reports, and databases
- Opening and Closing Files
open() Function
Used to open a file.
file = open("example.txt", "r")
File Object
The open() function returns a file object that is used to perform operations.
Closing Files
file.close()
Using with Statement (Best Practice)
Automatically closes the file.
with open("example.txt", "r") as file:
data = file.read()
Key Points
- Always close files after use
- Use
withto avoid memory leaks
- Reading Files
read() Method
Reads the entire file.
read() Method
//Reads the entire file.
with open("example.txt", "r") as file:
content = file.read()
print(content)
readline() Method
//Reads one line at a time.
with open("example.txt", "r") as file:
line = file.readline()
print(line)
readlines() Method
//Reads all lines into a list.
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
//Reading Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
- Writing Files
write() Method
//Writes data to a file.
with open("example.txt", "w") as file:
file.write("Hello Python")
writelines() Method
lines = ["Line 1\n", "Line 2\n"]with open("example.txt", "w") as file:
file.writelines(lines)
//Appending Data
with open("example.txt", "a") as file:
file.write("\nNew Line")
Overwriting Files
- Using
"w"mode deletes existing content - Use carefully to avoid data loss
- Working with File Modes
File modes define how a file is opened.
| Mode | Description |
|---|---|
| r | Read (default) |
| w | Write (overwrite) |
| a | Append |
| b | Binary mode |
| r+ | Read and write |
| w+ | Write and read |
| a+ | Append and read |
Examples
("file.txt", "w")# Append mode
open("file.txt", "a")
//Binary Mode Example
with open("image.jpg", "rb") as file:
data = file.read()
Conclusion
File handling is a crucial skill in Python programming, as it enables programs to interact with external data stored on a system. By learning how to open, read, write, and manage files, learners can build applications that store and process real-world data efficiently.
Understanding file modes and best practices like using the with statement ensures safe and efficient file operations. Mastering file handling is essential for advanced topics such as data analysis, web development, and automation.
This module provides a strong foundation for working with files, which is a key requirement in most real-world Python applications.
Leave a Reply