Posted on 6/18/2025 5:45:56 PM by Admin

File Handling in Python: Reading and Writing Files

In our last article, we dived deep into creating user-defined functions with parameters and return statements to build more robust and resilient applications. Before that, we also discussed storing data in data structures like dictionaries, tuples, lists, and sets, but what if you want to keep data even after closing the program? This is where File handling comes into play.

File I/O (Input/Output) is a way to interact with the files stored on your computer using Python. It allows you to save your program data permanently, read configurations from external files, and process large datasets that are impossible to fit in the program's memory. Remember that each program is assigned a limited memory when in execution, and it overflows if you store large datasets in it. Therefore, understanding file handling is crucial to writing memory-efficient programs. In this article, you will learn how to open, read, write, and close files properly in Python to ensure data integrity.


Understanding File Paths

The file path is the location of a file on your computer. It tells the program where a file is stored in computer memory. There are two types of paths that you can use to locate a file:

  1. Absolute path
  2. Relative path

1. Absolute Path

The absolute path contains the complete hierarchy of directories to the required file starting from the root directory.

  • On Windows, it looks like: C:\Users\YourUser\Documents\my_data.txt.
  • On Linux/macOS, it appears as: /home/youruser/documents/my_data.txt

Although absolute paths are precise, they can make your code less portable if the file structure changes.

2. Relative Path

A relative path provides the location of the file relative to the current working directory. If the file is in the same folder as the program itself, only the filename.extension is enough to access it. If it's inside another folder in the same directory, the folder_name/filename.extension can be used to access it.

Current Working Directory

This is the folder in which your program is stored and is currently operating. You can check your current working directory using the os module as follows:


import os
print(os.getcwd())

Output:


F:\Work\Python bootcamp\pythonProject

Please note that your output will be different, reflecting your current working directory.

Path Separators

A path separator is a symbol that operating systems use to separate the directories within the path. Different operating systems use different path separators. Windows uses the backslash(\), whereas Linus and macOS use the forward slash (/). However, Python is intelligent enough to handle this. Therefore, it is considered a good practice to use forward slash (/) even on Windows.


Opening and Closing Files

When you want to work on a file, you must open it to establish a connection between the file and your program. Once you are done, you must close the file to ensure file safety.

Opening a File: The open() Function

The open() function allows you to access a file using Python. It takes two arguments, i.e., the filename (path) and the mode of operation.

Syntax:


file_object = open(filename, mode)

In the above syntax,

  • filename refers to the path of the file.
  • mode refers to the operation you want to perform on the file. The value of the mode can be:
    • 'r' (Read Mode): Allows you to only read the content of the file. You can not make any changes to it.
    • 'w' (Write Mode): Allows you to open the file in write mode. You can add new content or edit the existing file content in this mode. If the file does not exist, a new blank file is created in the specified location.
    • 'a' (Append Mode): Opens the file in write mode. If the file exists, the new content is added to the end of the file. If not, a new file is created, and the content is added to it.
    • 'x' (Exclusive Creation Mode): Creates a new file with writing mode. If the file already exists, it throws the FileExistsError.

There are other modes as well, but these are the most commonly used.

Example:


try:
    my_file = open("my_document.txt", "r")
    print("File opened successfully!")
except FileNotFoundError:
    print("Error: my_document.txt not found.")

In the above example, I have placed the code for opening the file in read mode inside the try block because it may throw the FileNotFoundError exception if the file does not exist.

Closing the File: The close() function

The close() function is used to close the file after you have completed the operation.

Syntax:


file_object.close()

Closing a file is highly essential to save system resources. Also, when you write something to a file, it is held in the buffer memory and is not actually written to the file unless you close it. However, there can be times when an error occurs during the opening and closing of the file, ultimately leaving the file open and leading to a resource leak. So, how to deal with such a situation? The answer is using the 'with' statement.

The 'with' Statement

The 'with' statement is the ultimate solution to all the errors that might occur during file operations. It is the safest and most recommended way to handle files in Python. It behaves as a context manager that ensures that the files are automatically closed regardless of any errors.

Opening a file with 'with'

Syntax:


with open(filename,mode) as file_object:
    # Perform file operations

In the above code, the file will automatically close once the interpreter gets out of the block.


Performing File Operations

Now that we know how to open and close files promptly, it's time to explore some file operations:

Opening a File in Read Mode


with open("my_document.txt", "r") as read_file:
    print("File opened successfully!")

Currently, you can see that our file is empty.

Opening a File in Write Mode


with open("my_document.txt", "w") as write_file:
    write_file.write("This is the text written by the Python file")
    write_file.write("Good Bye!")

The above code writes the text in the following file:

Text added to the file by program
Text added to the file by program

Opening a File in Append Mode


with open("my_document.txt", "a") as append_file:
    append_file.write("\nWelcome Back!")
    append_file.write("\nThis is the appended text!")

You can see that the new text has been appended to our file:

Text appended to the file by program
Text appended to the file by program

Reading From Files

You can read the contents of a file with the read() function.


with open("my_document.txt", "r") as read_file:
    contents = read_file.read()
    print(contents)

Output:


This is the text written by the Python fileGood
Bye!

Welcome Back!

This is the appended text!

Reading a Single Line at a Time

You can retrieve one line at a time using the readline() method.


with open("my_document.txt", "r") as read_file:
    content1 = read_file.readline()
    content2 = read_file.readline()
    print(content1)
    print(content2)

Output:


This is the text written by the Python fileGood
Bye!

Welcome Back!

I think this is a good head start with the file handling in Python. You'll explore much more in file handling as you advance, but this is enough to know at the beginner level. Now, you can create, read, write, and close files in Python easily. In the next article, we will get started with modules and packages in Python.


Sharpen Your Skills with These Next Guides