๐Ÿ“‚ Mastering File Handling in Python: Read, Write, and Delete Files Like a Pro

Jugal kishoreJugal kishore
3 min read

1. ๐Ÿ” Mastering File Reading in Python: read(), readline(), and readlines() Explained

Python offers three powerful methods to read content from a file: read(), readline(), and readlines(). Each has specific use cases.

โœ… read()

  • Purpose: Reads the entire content of the file as a single string.

  • Use case: Best for small files when you want all data at once.

      with open("sample.txt", "r") as file:
          content = file.read()
          print(content)
    

    ๐Ÿ“ค Output:

  •   Hello, this is line 1
      This is line 2
      And this is line 3
    

โœ… readline()

  • Purpose: Reads one line at a time.

  • Use case: Useful for reading large files line by line to save memory.

      with open("sample.txt", "r") as file:
          line1 = file.readline()
          line2 = file.readline()
          print(line1.strip())
          print(line2.strip())
    

    ๐Ÿ“ค Output:

      Hello, this is line 1
      This is line 2
    

โœ… readlines()

  • Purpose: Reads all lines into a list where each line is an item.

  • Use case: Convenient when you want to loop through lines.

      with open("sample.txt", "r") as file:
          lines = file.readlines()
          for line in lines:
              print(line.strip())
    

    ๐Ÿ“ค Output:

      Hello, this is line 1
      This is line 2
      And this is line 3
    

2. ๐Ÿ“ Writing and Managing Files in Python: Creating, Writing, and Closing Files

Writing to files in Python is just as simple as reading. You use modes like 'w' (write) or 'a' (append).

โœ๏ธ Create & Write a New File

with open("output.txt", "w") as file:
    file.write("This is a new file.\n")
    file.write("It contains some text.")
  • 'w' mode will create the file if it doesn't exist, or overwrite it if it does.

๐Ÿ“ output.txt content:

This is a new file.
It contains some text.

โž• Append to a File

with open("output.txt", "a") as file:
    file.write("\nThis is an appended line.")

๐Ÿ“ Updated output.txt:

This is a new file.
It contains some text.
This is an appended line.

โ— Closing Files

When using with open(...), Python automatically closes the file. If not, always remember to close manually:

file = open("example.txt", "w")
file.write("Hello world!")
file.close()

โœ… Best Practice: Always prefer with block to handle file closing safely.


3. ๐Ÿ—‘๏ธ How to Delete Files Using Pythonโ€™s os Module: A Practical Guide

Sometimes, you need to remove files after processing. Pythonโ€™s os module helps you safely do this.

๐Ÿ”ง Step-by-Step Deletion

import os

file_path = "output.txt"

# Check if file exists before deleting
if os.path.exists(file_path):
    os.remove(file_path)
    print("File deleted successfully.")
else:
    print("File does not exist.")

๐Ÿ“Œ This avoids errors like:

FileNotFoundError: [Errno 2] No such file or directory

โš ๏ธ Important Tips

  • Use os.remove() only for files, not folders.

  • To delete directories, use os.rmdir() (for empty folders) or shutil.rmtree() (for non-empty folders).

import shutil

# To delete a folder and its contents
shutil.rmtree("example_folder")

๐Ÿš€ Wrapping Up

Mastering file handling in Python opens up a lot of possibilitiesโ€”from simple automation to full-fledged data processing apps. Here's a quick summary:

ActionMethodNotes
Read entire fileread()Loads all content at once
Read line by linereadline()Reads one line per call
Read lines as listreadlines()Returns list of all lines
Write to filewrite()Overwrites or appends
Delete fileos.remove()Check with os.path.exists()/
0
Subscribe to my newsletter

Read articles from Jugal kishore directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jugal kishore
Jugal kishore