File Handling | Dataplexa

File Handling in Python

File handling is one of the most important parts of Python programming. It allows your programs to read information from files and save data into files. Understanding how to work with files is necessary for real projects like data processing, logging, automation, and more.

Why Do We Use File Handling?

File handling helps you:

  • Store information permanently
  • Read data from a text file or log file
  • Save user input or program output
  • Work with large data files in real applications

Opening a File in Python

Python provides the open() function to interact with files. You must specify the file name and the mode (read, write, append, etc.).

Common File Modes:

  • "r" – Read mode (default)
  • "w" – Write mode (overwrites file)
  • "a" – Append mode (adds data to end)
  • "r+" – Read and write

Reading a File

To read the contents of a file:

file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()

This reads the entire file and prints it.

Reading File Line by Line

You can also read a file one line at a time:

file = open("sample.txt", "r")

for line in file:
    print(line)

file.close()

Writing to a File

Write mode "w" creates the file if it doesn’t exist and overwrites it if it does.

file = open("output.txt", "w")
file.write("Hello, Dataplexa!")
file.close()

Appending to a File

Append mode "a" adds text to the end of the file instead of overwriting it.

file = open("output.txt", "a")
file.write("\nThis line was appended.")
file.close()

Using the with Statement

The with statement automatically handles opening and closing the file. This is the safest and most recommended way to work with files in Python.

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

Advantage: No need to manually close the file. Python closes it automatically.

Writing Using with

with open("notes.txt", "w") as file:
    file.write("This file was created using 'with'.")

Check If a File Exists

You can check file existence using the os module.

import os

if os.path.exists("data.txt"):
    print("File found")
else:
    print("File not found")

Handling File Not Found Error

try:
    file = open("missing.txt", "r")
    print(file.read())
except FileNotFoundError:
    print("The file does not exist")

Real-World Example: Saving User Data

This example collects user input and saves it to a file.

name = input("Enter your name: ")
email = input("Enter your email: ")

with open("users.txt", "a") as f:
    f.write(f"{name}, {email}\n")

print("User saved successfully!")

📝 Practice Exercises


Exercise 1

Create a file named hello.txt and write “Welcome to Python File Handling”.

Exercise 2

Write a Python program to read a file and count how many characters it has.

Exercise 3

Append three new lines to a file called log.txt.

Exercise 4

Write a program that checks if notes.txt exists. If yes, read it. If not, create it and write a welcome message.


✅ Practice Answers


Answer 1

with open("hello.txt", "w") as file:
    file.write("Welcome to Python File Handling")

Answer 2

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

Answer 3

with open("log.txt", "a") as file:
    file.write("First line added\n")
    file.write("Second line added\n")
    file.write("Third line added\n")

Answer 4

import os

if os.path.exists("notes.txt"):
    with open("notes.txt", "r") as file:
        print(file.read())
else:
    with open("notes.txt", "w") as file:
        file.write("Welcome! This file was created because it did not exist.")
    print("File created successfully.")