Python File Handling Explained: Read, Write, and Manage Files

 Python File Handling Explained: A Complete Beginner’s Guide

Python is one of the most popular programming languages for automation, data analysis, web development, and software development. One important skill every Python developer should learn is file handling.

Python file handling tutorial with folders, documents, and programming code

Think about your daily computer activities. You create documents, save reports, read text files, update Excel sheets, and organize folders. Python can perform many of these tasks automatically.

For example, Python can read information from a text file, create a new report, update an existing file, or organize hundreds of files into different folders.

This is where Python file handling becomes useful.

In this beginner-friendly guide, you will learn what file handling is, how to open and close files, how to read and write data, and how to manage files using simple Python examples.

By the end of this tutorial, you will understand how to work with files in Python and use these skills in real-world automation projects.

1. What Is File Handling in Python?

File handling in Python is the process of creating, opening, reading, writing, updating, and closing files using Python code.

A file stores information permanently on your computer or another storage device. Unlike a normal Python variable, which generally exists only while your program is running, a saved file can be accessed later.

For example, suppose you have a text file called employees.txt that contains employee information.

Python can read that information, display it, add new employee details, or save updated information in another file.

File handling is commonly used for:

  • Reading text files.
  • Creating new files.
  • Writing information into files.
  • Updating existing information.
  • Managing log files.
  • Saving reports.
  • Processing CSV files.
  • Automating file and folder management.

Simple example:

file = open("example.txt", "r")
content = file.read()

print(content)

file.close()

In this example, Python opens a file, reads its content, displays the information, and closes the file.

We will understand each part step by step.

2. Understanding the Python open() Function

Python provides a built-in function called open() to work with files.

The open() function connects your Python program to a file so you can perform operations such as reading or writing.

Syntax:

open(file, mode)

There are two important parameters:

  • file: The name or path of the file you want to access.
  • mode: The operation you want to perform, such as reading or writing.

Example:

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

Here:

  • data.txt is the file name.
  • "r" means read mode.
  • Python tries to open the file for reading.

If the file does not exist, read mode raises a FileNotFoundError.

3. Different File Modes in Python

File modes tell Python what you want to do with a file.

Infographic explaining Python file modes read, write, append, and create.


The following are the most commonly used modes:

ModeMeaningBehaviour
rReadReads an existing file
wWriteCreates or overwrites a file
aAppendAdds content at the end
xCreateCreates a new file and fails if it already exists
r+Read and writeOpens an existing file for both operations
w+Write and readCreates or overwrites a file
a+Append and readReads and appends to a file

Python also supports additional mode characters:

  • b: Binary mode, used for files such as images and PDFs.
  • t: Text mode, which is the default.

You can combine these characters with other modes. For example, rb means reading a file in binary mode.

Important: Be careful when using "w" mode. It removes the existing content of a file before writing new content.



4. How to Read a File in Python

Reading a file means accessing the information already stored inside it.

Python reading information from a text file using code.

Python provides several methods to read file content.

A. Using read()

The read() method reads the content of a file and returns it as a string.

Example:

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

content = file.read()

print(content)

file.close()

Suppose data.txt contains:

Welcome to ITTech Language.
Python is easy to learn.
File handling is an important Python concept.

Output:

Welcome to ITTech Language.
Python is easy to learn.
File handling is an important Python concept.

You can also specify the number of characters you want to read.

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

content = file.read(10)

print(content)

file.close()

This reads the first 10 characters from the file.

B. Using readline()

The readline() method reads one line at a time.

Example:

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

line = file.readline()

print(line)

file.close()

If the file contains three lines, this example reads only the first line.

You can call readline() again to read the next line.

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

print(file.readline())
print(file.readline())

file.close()

This displays the first two lines.

C. Using readlines()

The readlines() method reads all lines and returns them as a list.

Example:

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

lines = file.readlines()

print(lines)

file.close()

Output:

[
    'Welcome to ITTech Language.\n',
    'Python is easy to learn.\n',
    'File handling is important.\n'
]

Each line is stored as a separate list item. The \n character represents a line break.

When should you use these methods?

  • Use read() when you want to read the complete content as one string.
  • Use readline() when you want to read one line at a time.
  • Use readlines() when you need all lines as a list.

For very large files, reading line by line is usually more memory-efficient than loading the entire file into memory.

5. How to Write a File in Python

Writing means adding new information to a file.

Python uses the "w" mode to write content.

Example:

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

file.write("Name: Rahul\n")
file.write("Course: Python Programming\n")
file.write("Institute: ITTech Language\n")

file.close()

This code creates student.txt if it does not exist.

If the file already exists, its previous content will be overwritten.

The write() method returns the number of characters written.

Writing Multiple Lines

You can also write multiple lines using writelines().

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

data = [
    "Rahul\n",
    "Amit\n",
    "Priya\n",
    "Neha\n"
]

file.writelines(data)

file.close()

The writelines() method does not automatically add line breaks. That is why \n is included in each item.

Remember: Use "w" only when you want to replace the existing file content.

6. How to Append Data to a File in Python

Sometimes you do not want to remove the existing information. You only want to add new data at the end.

Difference between writing and appending content in Python files.

For this purpose, Python provides append mode "a".

Example:

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

file.write("Employee Name: Mohit\n")
file.write("Department: Operations\n")

file.close()

This adds new information to the end of the file without deleting its existing content.

Difference Between Write and Append

Write Mode (w)Append Mode (a)
Creates a file if it does not existCreates a file if it does not exist
Replaces existing contentKeeps existing content
Writes from the beginningAdds content at the end
Useful for creating fresh reportsUseful for logs and records

For example, an application that records daily activities can use append mode to keep adding new log entries without deleting previous records.

7. How to Create a New File Using Python

Python provides "x" mode to create a new file.

Example:

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

file.write("This is my first Python file.")

file.close()

This creates a new file named newfile.txt.

However, if the file already exists, Python raises a FileExistsError.

You can handle this situation using exception handling.

try:
    file = open("newfile.txt", "x")
    file.write("Welcome to Python file handling.")
    file.close()

    print("File created successfully.")

except FileExistsError:
    print("File already exists.")

This prevents the program from stopping unexpectedly when the file already exists.

8. How to Close a File in Python

After completing file operations, it is important to close the file.

The close() method closes an opened file.

Example:

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

content = file.read()

print(content)

file.close()

Why should you close a file?

  • It releases system resources.
  • It helps ensure buffered data is written properly.
  • It prevents unnecessary open file connections.
  • It reduces the risk of file-related problems.

However, manually closing files can sometimes be forgotten, especially when an error occurs.

A better approach is to use Python's with statement.

9. Using the with Statement for File Handling

The with statement is the recommended way to open files in Python.

It automatically closes the file when the block finishes, even if an exception occurs.

Example:

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

Notice that we do not need to call file.close().

Python handles the closing process automatically.

Writing with the with Statement

with open("report.txt", "w") as file:
    file.write("Monthly Sales Report\n")
    file.write("Total Sales: 50000\n")

Appending with the with Statement

with open("report.txt", "a") as file:
    file.write("New Sales: 15000\n")

Using with makes your code cleaner, safer, and easier to maintain.

10. Understanding File Paths in Python

A file path tells Python where a file is located.

There are two common types of file paths.

A. Relative Path

A relative path points to a file based on the current working directory.

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

Here, Python looks for data.txt in the current working directory.

B. Absolute Path

An absolute path provides the complete location of a file.

Windows example:

with open("C:/Users/YourName/Documents/data.txt", "r") as file:
    print(file.read())

Linux example:

with open("/home/username/documents/data.txt", "r") as file:
    print(file.read())

You can also use the pathlib module to work with file paths in a cleaner and more portable way.

from pathlib import Path

file_path = Path("data.txt")

if file_path.exists():
    print(file_path.read_text())
else:
    print("File not found.")

The pathlib module is useful when building file automation projects because it provides convenient methods for working with files and folders.

11. How to Check Whether a File Exists

Before reading a file, it is often useful to check whether it exists.

Python provides the os module and the pathlib module for this purpose.

Using os.path.exists()

import os

file_name = "data.txt"

if os.path.exists(file_name):
    print("File exists.")
else:
    print("File does not exist.")

Using pathlib

from pathlib import Path

file_path = Path("data.txt")

if file_path.exists():
    print("File exists.")
else:
    print("File does not exist.")

Both methods help prevent errors when working with files that may not be available.

12. How to Delete a File Using Python

Python allows you to delete files using the os module.

The os.remove() function removes a file.

Example:

import os

file_name = "old_data.txt"

if os.path.exists(file_name):
    os.remove(file_name)
    print("File deleted successfully.")
else:
    print("File not found.")

Important: File deletion is permanent in many normal workflows. Always check the file path before deleting anything.

You can also use Path.unlink() from the pathlib module.

from pathlib import Path

file_path = Path("old_data.txt")

if file_path.exists():
    file_path.unlink()
    print("File deleted.")

13. How to Rename a File Using Python

Python automation organizing documents into different folders.


You can rename a file with the os.rename() function.

Example:

import os

os.rename("old_name.txt", "new_name.txt")

print("File renamed successfully.")

This changes the file name from old_name.txt to new_name.txt.

You can also use pathlib:

from pathlib import Path

old_file = Path("old_name.txt")
new_file = Path("new_name.txt")

if old_file.exists():
    old_file.rename(new_file)
    print("File renamed successfully.")

Always make sure the destination name and location are correct before renaming files.

14. Handling File Errors in Python

While working with files, you may face different types of errors.

For example:

  • The file does not exist.
  • You do not have permission to access a file.
  • The file is already open in another process.
  • You are trying to perform an unsupported operation.
  • The file path is incorrect.

Python provides exception handling to manage these situations.

Common File Handling Errors

ErrorMeaning
FileNotFoundErrorThe requested file does not exist
PermissionErrorYou do not have permission to access the file
FileExistsErrorA file or directory with that name already exists
IsADirectoryErrorYou tried to open a directory as a file
UnicodeDecodeErrorPython could not decode text using the selected encoding

Example Using try and except

try:
    with open("data.txt", "r", encoding="utf-8") as file:
        content = file.read()
        print(content)

except FileNotFoundError:
    print("The file does not exist.")

except PermissionError:
    print("You do not have permission to access this file.")

except UnicodeDecodeError:
    print("Unable to read the file using UTF-8 encoding.")

This code handles common errors and displays useful messages instead of allowing the program to stop unexpectedly.

15. Reading and Writing Files with UTF-8 Encoding

Encoding defines how text characters are stored and interpreted.

When working with English, Hindi, or other languages, encoding becomes important.

A common encoding is UTF-8.

Example:

with open("language.txt", "w", encoding="utf-8") as file:
    file.write("Welcome to ITTech Language.\n")
    file.write("Python सीखना आसान है।")

with open("language.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

Using encoding="utf-8" helps Python correctly handle a wide range of characters.

For text files, specifying UTF-8 explicitly is a good habit when you control how the file is created and read.

16. Practical Python File Handling Project: Create a Simple Student Record System

Now let's combine what we have learned into a small practical project.

Suppose you want to store student names and marks in a text file.

The program will:

  1. Ask the user for a student name.
  2. Ask for the student's marks.
  3. Save the details in a text file.
  4. Read and display all saved records.

Python code:

file_name = "student_records.txt"

name = input("Enter student name: ")
marks = input("Enter student marks: ")

with open(file_name, "a", encoding="utf-8") as file:
    file.write(f"Name: {name}, Marks: {marks}\n")

print("\nStudent record saved successfully.")

print("\nAll Student Records:")

with open(file_name, "r", encoding="utf-8") as file:
    records = file.read()

    if records:
        print(records)
    else:
        print("No student records found.")

Example output:

Enter student name: Rahul
Enter student marks: 85

Student record saved successfully.

All Student Records:

Name: Rahul, Marks: 85

Every time you run this program, it adds a new record to the file.

This is a simple example of how Python file handling can be used to store information permanently.

17. Real-World Applications of Python File Handling

File handling is not limited to basic programming exercises. It is also used in real-world business and automation tasks.

Here are some common examples.

1. Report Generation

Python can read business data, calculate results, and save reports automatically.

For example, an operations team can generate a daily pickup and delivery report.

2. Log File Management

Applications generate log files to record activities, errors, and system events.

Python can read these logs and identify important information.

3. File Organization

Python can automatically organize files into folders based on their extensions.

For example:

  • PDF files into a PDF folder.
  • Images into an Images folder.
  • Excel files into an Excel folder.
  • Text files into a Text folder.

4. Data Processing

Python can read text or CSV files, process the information, and create updated files.

This is useful for data cleaning and reporting.

5. Backup Automation

Python can copy important files from one folder to another and help automate basic backup tasks.

6. Business Operations

Python can process employee records, delivery reports, sales data, and daily operational files.

These tasks can reduce repetitive manual work and save time.

18. Important Python File Handling Methods

Here is a quick reference to the file methods covered in this tutorial.

MethodPurpose
open()Opens a file
read()Reads file content
readline()Reads one line
readlines()Reads all lines into a list
write()Writes text into a file
writelines()Writes multiple strings
close()Closes an opened file
seek()Changes the file position
tell()Returns the current file position
flush()Flushes buffered data

Example of seek() and tell()

The tell() method returns the current position of the file cursor.

The seek() method changes the cursor position.

with open("data.txt", "r", encoding="utf-8") as file:
    print("Current position:", file.tell())

    print(file.read(5))

    print("New position:", file.tell())

    file.seek(0)

    print(file.read())

Here, seek(0) moves the cursor back to the beginning of the file.

These methods are helpful when you need more control over reading and writing operations.

19. Common Mistakes Beginners Should Avoid

When learning file handling, beginners often make a few common mistakes.

1. Forgetting to close a file

Use the with statement to ensure the file closes automatically.

2. Using the wrong file mode

Remember that "w" overwrites existing content, while "a" adds content at the end.

3. Providing an incorrect file path

Check the file location and spelling before opening it.

4. Reading a file that does not exist

Check whether the file exists or handle FileNotFoundError.

5. Forgetting line breaks

Use \n when you want to write information on separate lines.

6. Ignoring character encoding

Use an appropriate encoding, such as UTF-8, when working with text.

7. Loading very large files into memory

For large files, consider processing one line at a time instead of using read() for the entire file.

20. How to Practise Python File Handling

The best way to understand file handling is to practise small projects.

Here are some beginner-friendly exercises:

  • Create a text file and write your name and address.
  • Read a file and count the number of characters.
  • Add new records to an existing file.
  • Create a program that stores student marks.
  • Check whether a file exists before reading it.
  • Rename a file using Python.
  • Delete an unwanted file after confirming its name.
  • Create a simple daily activity log.

Once you understand these concepts, you can move towards more advanced automation projects using Python.

Frequently Asked Questions (FAQs)

1. What is file handling in Python?

File handling is the process of creating, opening, reading, writing, updating, and managing files using Python.

2. What is the use of the open() function in Python?

The open() function is used to access a file so Python can perform operations such as reading or writing.

3. What is the difference between "w" and "a" mode?

The "w" mode overwrites existing content, while "a" mode adds new content at the end of the file.

4. What happens if a file does not exist in read mode?

Python raises a FileNotFoundError when you try to open a non-existent file in "r" mode.

5. Why is the with statement used in Python file handling?

The with statement automatically closes a file after the block finishes, making file handling safer and cleaner.

6. What is the difference between read() and readline()?

The read() method reads the file content, while readline() reads one line at a time.

7. How can I create a file using Python?

You can use "w" mode to create or overwrite a file, or "x" mode to create a new file without overwriting an existing one.

8. How do I delete a file using Python?

You can use os.remove() or Path.unlink() to delete a file.

9. What is UTF-8 encoding in Python?

UTF-8 is a character encoding standard that allows text files to store and represent a wide range of characters and languages.

10. Is Python file handling useful for automation?

Yes. Python file handling is useful for report generation, file organization, log management, data processing, and backup automation.

Conclusion

Python file handling is an important concept for anyone learning Python programming or automation.

It allows you to work with files directly from your code. You can create new files, read existing information, write new content, append records, rename files, and delete unwanted files.

In this tutorial, we covered the open() function, different file modes, reading and writing methods, the with statement, file paths, exception handling, and a practical student record project.

Start with small examples and practise each file operation. Once you understand the basics, you can use file handling to build useful automation projects and solve real-world problems.

Keep learning and keep practising with ITTech Language!

Post a Comment

Ask any query by comments

Previous Post Next Post