Artificial Intelligence

Module 2.15 : File Handling in Python

Introduction

In programming, data often needs to be stored permanently instead of disappearing after program execution.

Python provides a powerful feature called File Handling that allows programmers to create, read, write, update, and manage files.

File handling is extremely important in Artificial Intelligence, Data Science, Machine Learning, Automation, and Software Development because applications frequently work with external data files.

For example:

  • Machine Learning datasets are stored in files.
  • AI applications save prediction results.
  • Web applications store logs.
  • Programs save reports and documents.

In this tutorial, you will learn File Handling in Python including file modes, reading files, writing files, append operations, file methods, and practical applications.


Learning Objectives

  • Understand file handling in Python.
  • Open and close files.
  • Read files using different methods.
  • Write and append data.
  • Understand file modes.
  • Work with text files.
  • Apply file handling in real-world applications.

What is File Handling in Python?

File handling is the process of working with files using programming.

Python allows developers to:

  • Create files
  • Read files
  • Write files
  • Update files
  • Delete files

Files help store data permanently.

Without file handling, program data would disappear after execution.


Why File Handling is Important

File handling is important because many real-world applications need persistent storage.

File handling is used in:

  • Machine Learning datasets
  • AI prediction storage
  • Student management systems
  • Banking software
  • Log files
  • Automation reports

Python programs frequently read and write files during data processing.


Opening Files in Python

Python uses the open() function to work with files.

Syntax

open(filename, mode)

Example

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

Here:

  • data.txt → file name
  • r → file mode

File Modes in Python

Python supports different file modes.

Mode Description
r Read Mode
w Write Mode
a Append Mode
x Create Mode
r+ Read and Write Mode

Read Mode (r)

Read mode is used to read existing files.

Example

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

print(file.read())

Output:

Contents of demo.txt file

If the file does not exist, Python generates an error.


Write Mode (w)

Write mode creates or overwrites a file.

Example

file = open("demo.txt","w")

file.write("Welcome to Python")

This writes data into the file.

If the file already exists, previous data is removed.


Append Mode (a)

Append mode adds new content without deleting old data.

Example

file = open("demo.txt","a")

file.write("New Line Added")

Create Mode (x)

Create mode creates a new file.

Example

file = open("newfile.txt","x")

If the file already exists, Python generates an error.


Closing Files

Files should be closed after operations.

Python uses the close() method.

Example

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

print(file.read())

file.close()

Closing files helps release system resources.


Reading Files in Python

Python provides several methods for reading files.

1. read()

Reads entire file content.

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

print(file.read())

2. readline()

Reads one line at a time.

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

print(file.readline())

3. readlines()

Reads all lines into a list.

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

print(file.readlines())

Writing Files in Python

The write() method writes data into a file.

Example

file = open("student.txt","w")

file.write("John")

Using with Statement

Python provides the with statement for safe file handling.

It automatically closes files.

Example

with open("demo.txt","r") as file:

    print(file.read())

This approach is recommended in professional programming.


Deleting Files

Python uses the os module for deleting files.

Example

import os

os.remove("demo.txt")

Checking File Existence

Before deleting a file, checking whether it exists is recommended.

Example

import os

if os.path.exists("demo.txt"):

    os.remove("demo.txt")

else:

    print("File Not Found")

File Handling in Artificial Intelligence

File handling is extremely important in Artificial Intelligence and Data Science.

Common applications:

  • Reading CSV datasets
  • Saving trained models
  • Loading configuration files
  • Saving prediction outputs
  • Generating AI reports

Machine Learning projects frequently load data files for model training.


Real-World Examples

Student Record Example

with open("student.txt","w") as file:

    file.write("John,85,Science")

AI Prediction Log Example

with open("prediction_log.txt","a") as file:

    file.write("Prediction Completed\n")

Python Example

with open("sample.txt","w") as file:

    file.write("Learning Python File Handling")

with open("sample.txt","r") as file:

    print(file.read())

Output:

Learning Python File Handling

Interview Questions

1. What is file handling in Python?

File handling is the process of creating, reading, writing, and managing files.

2. Which function opens files?

The open() function.

3. Which mode appends data?

The a mode.

4. Why is the with statement preferred?

Because it automatically closes files safely.


Assignment

  1. Create a file and write student data.
  2. Read file contents using read().
  3. Use append mode to add new data.
  4. Create a file using x mode.
  5. Delete a file using os.remove().

Quiz

Q1. Which function opens files?

  • A. file()
  • B. read()
  • C. open()
  • D. create()

Answer: C. open()

Q2. Which mode writes data and overwrites files?

  • A. r
  • B. a
  • C. w
  • D. x

Answer: C. w

Q3. Which mode appends new content?

  • A. a
  • B. r
  • C. x
  • D. +

Answer: A. a


Summary

In this tutorial, you learned File Handling in Python. You explored file modes, opening files, reading files, writing files, appending content, deleting files, and safe file handling using the with statement.

File handling is a fundamental skill in Artificial Intelligence, Data Science, Automation, and software development because modern applications constantly interact with external data files.

Next Tutorial

Module 3: Data Science Fundamentals
Tutorial 21: What is Data Science?

“`

Leave a Reply

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