Python

 

 

Introduction

File handling is a fundamental concept in Python that allows programmers to store and retrieve data from files.
Python provides built-in functions for reading from and writing to files, making it easy to manage external data
like text documents, logs, and more.

Objective

By the end of this tutorial, you will be able to:

  • Open and close files in Python
  • Read data from a text file
  • Write data to a text file
  • Understand the structure of a basic file handling program

Python Code: Reading and Writing Files

# File: file_operations.py

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, this is a file writing example in Python.\n")
    file.write("You can write multiple lines like this.\n")

# Reading from the file
with open("example.txt", "r") as file:
    content = file.read()
    print("File Content:\n")
    print(content)

Explanation of the Program

The program is divided into two parts:

  1. Writing to the File:
    • open("example.txt", "w") opens a file in write mode. If the file doesn’t exist, it will be created.
    • file.write() is used to write text into the file.
    • The with statement automatically handles closing the file.
  2. Reading from the File:
    • open("example.txt", "r") opens the file in read mode.
    • file.read() reads the entire content of the file into a string.
    • The content is printed to the console.

How to Run the Program

To execute the program:

  1. Open your text editor or IDE (like VSCode or PyCharm).
  2. Save the code in a file named file_operations.py.
  3. Open a terminal or command prompt.
  4. Navigate to the folder containing the file.
  5. Run the script by typing: python file_operations.py
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)