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:
- 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.
- 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:
- Open your text editor or IDE (like VSCode or PyCharm).
- Save the code in a file named
file_operations.py
. - Open a terminal or command prompt.
- Navigate to the folder containing the file.
- Run the script by typing:
python file_operations.py