File handling is a crucial concept in computer science, particularly when dealing with data storage and retrieval. In the CBSE syllabus, understanding file handling involves learning how to create, read, write, and manipulate files using various programming languages, with a focus on Python. This study note will help break down these concepts into manageable sections, providing examples and explanations to ensure a clear understanding.
A file is a collection of data stored in a storage device. It can contain text, images, videos, or any other type of data. Files are essential for storing data persistently, beyond the life of a program.
Files can be broadly categorized into two types:
.txt
, .csv
, and .html
files..exe
, .jpg
, and .dat
files.To perform any operation on a file, it must first be opened. In Python, the open()
function is used to open a file. The syntax is:
file_object = open("filename", "mode")
filename
: The name of the file you want to open.mode
: The mode in which you want to open the file.The different modes for opening a file are:
'r'
: Read mode (default). Opens the file for reading.'w'
: Write mode. Opens the file for writing (creates a new file if it does not exist or truncates the file if it exists).'a'
: Append mode. Opens the file for appending (creates a new file if it does not exist).'b'
: Binary mode. Used for binary files.'+'
: Update mode. Opens the file for both reading and writing.Tip
Combine modes like 'rb'
for reading binary files or 'w+'
for writing and reading.
To read from a file, you can use methods like read()
, readline()
, and readlines()
.
read(size)
: Reads the specified number of bytes from the file.readline()
: Reads a single line from the file.readlines()
: Reads all lines from the file and returns them as a list.Example
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
To write to a file, use the write()
or writelines()
methods.
write(string)
: Writes the specified string to the file.writelines(list_of_strings)
: Writes a list of strings to the file.Example
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
It is important to close a file after performing operations on it to free up system resources. This is done using the close()
method.
Note
Always close files to avoid memory leaks and other issues.
with
StatementThe with
statement in Python provides a way to automatically manage file resources. It ensures that the file is properly closed after its suite finishes, even if an exception is raised.
Example
with open("example.txt", "r") as file:
content = file.read()
print(content)
# No need to explicitly close the file
seek()
and tell()
seek(offset, whence)
: Moves the file pointer to a specified location.tell()
: Returns the current position of the file pointer.Example
file = open("example.txt", "r")
file.seek(5)
print(file.tell()) # Output: 5
file.close()
CSV (Comma Separated Values) files are a common format for storing tabular data. Python's csv
module provides functionality to read from and write to CSV files.
Example
import csv
with open("example.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Example
import csv
with open("example.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", "30", "New York"])
Common Mistake
Forgetting to close a file after opening it can lead to memory leaks.
Tip
Use the with
statement to handle files, as it ensures proper closure.
Common Mistake
Not handling exceptions while performing file operations can cause the program to crash.
Tip
Use try-except blocks to handle potential file I/O errors.
File handling is an essential skill in computer science, enabling persistent data storage and manipulation. By understanding the basic operations, file modes, and handling different types of files, you can effectively manage data in your programs. Practice these concepts with real-world examples to reinforce your learning.
This concludes our detailed study note on file handling. Happy coding!