fbpx

Best Practices for File Handling in Python: Writing Clean, Reliable Code

Best Practices for File Handling in Python: Writing Clean, Reliable Code


INTRODUCTION

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.

Basic File Handling Operations

Here are the basic operations involved in file handling:

  1. Opening a file
  2. Reading from a file
  3. Writing to a file
  4. Closing a file

Modes:

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.

Opening a File

Syntax:

file_object = open(file_name, mode)

  • file_name: The name (and path, if necessary) of the file you want to open.
  • mode:whether the user is reading from or writin to.

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 .”)

  1. read binary mode(rb)

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);

Reading  a  file

———————

  1. read()
  2. readline()
  3. readlines()

  Example 1:

The read() method reads the complete  content of the file.

With open(“hello.txt”,’r’) as file:

 content=file.read();

 print(content);

Example 2:

with open(“hello.txt”,”r”) as file:

  line=file.readline();

while line:

print(line,end=’ ‘);

line=file.readline();

Example 3:

# 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

Writing to a File Example

Example1(w)

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.”)

Example 2:

with open(‘example.txt’, ‘a’) as file:

    file.write(“This is an appended line.\n”)

    print(“Data ‘a’ mode.”)

Example 3:

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.”)

Explanation:
  1. Write mode ‘w’:
    • In the first block, example.txt is opened in write mode (‘w’), so any existing content in the file will be overwritten.
    • file.write() is used to write each line of text into the file.
    • After this operation, example.txt will contain only the lines we wrote here, overwriting any previous content.
  2. Append mode ‘a’:
    • In the second block, the file example.txt is opened in append mode (‘a’). This mode allows us to add content to the end of the file without modifying existing content.
    • We add a line of text, and it is appended at the end of the current contents of example.txt.
  3. Exclusive creation mode ‘x’:
    • In the third block, newfile.txt is opened in exclusive creation mode (‘x’). This mode ensures that the file is created only if it doesn’t already exist.
    • If the file does exist, a FileExistsError is raised, and we handle it with a try-except block.