File handling in Python

Key takeaways:

  • Importance: File handling is essential for reading, writing, and managing files in Python, enabling efficient data storage and processing.

  • File handling modes:

    • 'r': Read mode: raises an error if the file doesn’t exist.

    • 'w': Write mode; creates a new file or truncates an existing one.

    • 'a': Append mode; adds data to the end of the file.

    • 'x': Exclusive creation; raises an error if the file already exists.

    • 'b': Binary mode; used with read, write, or append.

    • 't': Text mode (default).

    • '+': Read and write mode.

  • File operations:

    • Opening files: Use open() to get a file object.

    • Reading files: Use read(), readline(), or readlines().

    • Writing files: Use write() or writelines().

    • Closing files: Always close files using close() or using a with statement for automatic closure.

  • Exception handling: Implement try-except blocks to gracefully manage file-related errors (e.g., missing files, permission issues).

File handling in Python is an important skill for developers. It allows reading, writing, and managing files easily. Python’s built-in functions make data storage and processing efficient. We can handle both text and binary files with simple commands, making working with files straightforward in Python.

Files in Python

Assume you’re creating a simple to-do list app. You want to save the tasks the user adds so they can check them later, even after closing the app. This is where file handling in Python helps. It lets you save the tasks to a file and load them again when the user opens the app, so they don’t lose their progress.

Let’s take a quick look at the different modes of file handling:

File handling modes

We need different file-handling modes in Python to control how we interact with files, depending on the task. Each mode specifies whether we want to read, write, or append data to a file and whether the file should be treated as text or binary. Let’s discuss each mode and its working description below:

Mode

Description

Practical Application

'r'

Opens the file for reading. If the file does not exist, it raises an error.

Reading a configuration file

'w'

Opens the file for writing. Thid creates a new file or truncates the existing file.

Writing user data or logs

'a'

Opens the file in append mode. Data is added to the end of the file.

Adding to an existing record, like appending new entries to a log file

'x'

Creates a new file. If the file already exists, it raises an error.

Creating a new user data file

'b'

Opens the file in binary mode. Used with 'r', 'w', or 'a'.

Reading or writing binary files, like image or audio files

't'

Opens the file in text mode (default mode).

Reading or writing plain text files, such as .txt files

'+'

Opens the file for both reading and writing.

Updating a file, like modifying or viewing a user profile in a file

Let’s discuss each mode with the example below:

1. Opening files in Python

In Python, files are opened using the built-in open() function, which takes two arguments: the file name and the mode (e.g., read, write, or append). This function returns a file object, which can be used to interact with the file.

Syntax

file = open('example.txt', 'r') # Open a file for reading

Opening a file using its full path

To open a file located in a different directory, we can use its full path in the open() function.

Example

file = open('C:/Users/username/Documents/example.txt', 'r')

This will open the file example.txt from the specified directory path.

2. Reading files in Python

We can read files in Python using the read(), readline(), or readlines() methods. These methods allow us to read the entire file, a single line, or all lines into a list, respectively.

Example

main.py
example.txt
Hello, this is a sample file.
Python makes file handling easy.
You can read, write, and manipulate files using the open() function.

Expand files, add some content, such as your name, to the example.txt file, and then click the "Run" button to see the results.

3. Writing to files in Python

To write data to a file, we can use the write() or writelines() methods. The write() method adds a single string, while writelines() can write multiple lines at once.

Example

main.py
example.txt
Hello, this is a sample file.
Python makes file handling easy.
You can read, write, and manipulate files using the open() function.

4. Closing files in Python

After performing file operations, it’s essential to close the file using the close() method. This ensures that the file is properly saved and all resources are freed.

Example

main.py
example.txt
file = open('example.txt', 'r')
# Perform operations
file.close() # Always close the file after use

Alternatively, using a with statement ensures the file is automatically closed after the block of code is executed:

Example

main.py
example.txt
with open('example.txt', 'r') as file: # Open the file in read mode using a context manager
content = file.read() # Read the entire content of the file
print(content) # Print the content of the file

5. Exception handling in Files

While handling files, errors such as missing files or permission issues can occur. We can use exception handling (try-except) to manage these situations gracefully.

Example

main.py
nonexistent.txt
try:
file = open('nonexistent.txt', 'r') # Try to open a file in read mode
except FileNotFoundError: # If the file is not found, handle the error
print("The file does not exist.") # Print an error message if the file is not found
finally:
if 'file' in locals(): # Check if the `file` variable exists in the local scope
file.close() # Close the file if it was opened successfully

Let’s discuss the advantages and disadvantages below:

Advantages of file handling in Python

  • Easy to use: Python provides simple functions to handle files, making it accessible for beginners.

  • Efficient: Python handles file operations quickly, even with large datasets.

  • Flexibility: Supports reading and writing different file formats (text, binary, etc.).

  • Cross-platform: Works across different operating systems without requiring complex setup.

Disadvantages of file handling in Python

  • Error-prone: File handling can lead to errors if not managed properly (e.g., forgetting to close a file).

  • Limited support for large files: For extremely large files, Python’s built-in functions may become slow or memory-intensive.

  • Security risks: Improper file handling can lead to security vulnerabilities, such as exposing sensitive information.

Let’s solve the quiz below:

1

What mode should you use to open a file for reading in Python?

A)

'w'

B)

'r'

C)

'a'

D)

'x'

Question 1 of 30 attempted

Ready to deepen your Python knowledge? Start our "Become a Python Developer" path, which begins with Python’s basic concepts and advances to more complex topics, preparing you for a career as a Python developer.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the use of the with statement in file handling in Python?

The with statement in Python simplifies file handling by automatically closing the file after the block of code is executed. It ensures that resources are properly released, even if an error occurs during file operations.


What is a tell() method in Python file handling?

The tell() method in Python returns the current position of the file pointer, which indicates where the next read or write operation will take place within the file.


How many types of files are there in Python?

In Python, there are two main types of files: text files (which store data in readable characters) and binary files (which store data in binary format, such as images or executables).


Why is file handling useful?

File handling is useful because it allows programs to store and retrieve data, maintain records, log information, and manage large datasets efficiently. It’s essential for persistent data storage between program runs.


How to start learn to code in Python

To start learning to code, choose a platform that offers interactive, hands-on lessons. Educative’s “Learn to Code” path helps beginners become job-ready with gamified, project-based content, making learning practical and engaging. Their step-by-step approach ensures you gain both knowledge and real-world skills.


What happens if you forget to close a file?

Forgetting to close a file can lead to data not being saved properly, causing potential data loss. It may also cause memory leaks and prevent other processes from accessing the file.


Free Resources