The basics of file handling in Python involve four main steps: opening a file, performing read or write operations, and then closing the file. Different modes can be used based on the requirements, such as reading, writing, appending, or working with binary data. This flexibility ensures that developers can handle files in various formats and with different types of content.
In this blog, we’ll explore essential file handling concepts in Python, including how to open, read, write, and close files, and understand the different file modes. We’ll walk through examples to show you how to manage file content effectively, whether it’s text, binary data, or even creating new files. Let’s dive into the world of Python file handling and see how it can enhance data management in your applications.
The process of reading from and writing to files in a system involves interacting with file content. Python offers built-in functions and methods to handle file operations, allowing you to work with both text and binary files.
Here are the basic operations involved in file handling:
r –(Reaing the file, the file should be present in the system)
w- writes the data to file if it exits it overwritten. if it not there or present inside the drive then it is created
‘a’ – Append mode:appends the data at the end without modifying the content
‘b’ – Binary mode: Opens the file in binary mode (e.g., ‘rb’, ‘wb’).
‘x’ – Exclusive creation: Creates a new file, but fails if the file already exists.
file_object = open(file_name, mode)
r : ( read only)
try:
with open(‘example.txt’, ‘r’) as file:
content = file.read()
print(“File Content in ‘r’ mode:”)
print(content)
except FileNotFoundError:
print(“File not found. Please ensure ‘example.txt’ exists.”)
2.write mode(w )
with open(‘example.txt’, ‘w’) as file:
file.write(“text.\n”)
print(“Data written to file .”)
3.append mode (a)
with open(‘example.txt’, ‘a’) as file:
file.write(“data appended.\n”)
print(“Data appended to file .”)
try:
with open(‘example.jpg’, ‘rb’) as file:
binary_data = file.read()
print(“Binary Data Read from ‘example.jpg’ .”)
except FileNotFoundError:
print(“File not found. Please ensure ‘example.jpg’ exists.”)
5.write binary(wb)
with open(‘new_image.jpg’, ‘wb’) as file:
file.write(b’\x89PNG\r\n\x1a\n’)
print(“Binary data written to ‘new_image.jpg’ “)
# 6. ‘x’ (exclusive creation) mode
try:
with open(‘new_file.txt’, ‘x’) as file:
file.write(“This file is newly created.”)
print(“File created successfully”)
except FileExistsError:
print(“File already exist”)
Writing a data to a file
—————————
# Writing to a file
with open(‘example.txt’, ‘w’) as file:
file.write(“text\n”)
# Appending to the file
with open(‘example.txt’, ‘a’) as file:
file.write(“This line is appended.\n”)
# Reading the file again
with open(‘example.txt’, ‘r’) as file:
content = file.read()
print(“Updated File Content:”)
print(content);
———————
The read() method reads the complete content of the file.
With open(“hello.txt”,’r’) as file:
content=file.read();
print(content);
with open(“hello.txt”,”r”) as file:
line=file.readline();
while line:
print(line,end=’ ‘);
line=file.readline();
# Open the file in read mode
with open(‘example.txt’, ‘r’) as file:
lines = file.readlines()
for line in lines:
print(line, end=”) # Print each line without adding an extra newline
writing a file:
—————-
Top of Form
Bottom of Form
with open(‘example.txt’, ‘w’) as file:
file.write(“This is the first line.\n”)
file.write(“This is the second line.\n”)
print(“Data ‘w’mode.”)
with open(‘example.txt’, ‘a’) as file:
file.write(“This is an appended line.\n”)
print(“Data ‘a’ mode.”)
try:
with open(‘newfile.txt’, ‘x’) as file:
file.write(“This file was created with ‘x’ mode.”)
print(” created and written”)
except FileExistsError:
print(“File already exists.”)
Indian Institute of Embedded Systems – IIES