Working with Files in Python: Reading and Writing Data

 

 

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.

 

Leave a Reply

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