Chapter 6: File Handling in Python

Abstract

File handling in Python refers to the ability to read from and write to files on your computer. It allows you to interact with external data sources, such as text files, CSV files, and more. 
Here's a breakdown of the key aspects of file handling in Python:
Opening a file:
You use the open() function to open a file. You need to specify the file name and the access mode (e.g., read, write, append).
Reading from a file:
You can use methods like read(), readline(), and readlines() to read the contents of a file.
Writing to a file:
You can use methods like write() and writelines() to write data to a file.
Closing a file:
It is essential to close a file when you are finished using it. This can be done using the close() method or by using the with statement.
Example:
Python

# Open a file for reading
with open("my_file.txt", "r") as f:
    # Read the entire file
    contents = f.read()
    print(contents)

# Open a file for writing
with open("new_file.txt", "w") as f:
    # Write some text to the file
    f.write("This is some text.\n")
    f.write("This is another line of text.\n")

File handling in Python is crucial for several reasons:
1. Data Persistence:
Storing and Retrieving Data:
Files allow you to store data permanently, even after your program terminates. This is essential for applications that need to save user information, configurations, logs, or any other data that needs to be accessed later.
Working with Large Datasets:
When dealing with datasets that are too large to fit in memory, files provide a way to process them in chunks, making your programs more efficient.
2. Data Interaction:
Reading Data from External Sources:
File handling enables you to read data from various sources, such as text files, CSV files, Excel spreadsheets, or even web APIs, allowing you to integrate external data into your programs.
Writing Data to External Destinations:
You can write data to files, which can then be used by other programs or systems. This is useful for generating reports, exporting data for analysis, or creating backups.
3. Application Functionality:
Configuration Management:
Files can be used to store application settings and configurations, making it easier to manage and modify them without changing the code.
Logging and Debugging:
By writing logs to files, you can track program execution, identify errors, and debug issues more effectively.
Building Complex Systems:
File handling is a building block for developing complex applications, such as web servers, data processing pipelines, and machine learning models.
4. Cross-Platform Compatibility:
Platform-Independent Data Exchange:
Files provide a platform-independent way to exchange data between different systems and operating systems.
Text-Based Formats:
Using text-based file formats like CSV or JSON allows you to share data with other programming languages and tools.
Keywords
File Handling in Python, Open a File in Python,  Reading a File, Writing to a File Python seek() function,  Python tell() function

Learning Outcomes 
After undergoing this chapter article you will be able to understand the following:
Overview 
Basics of File Handling in Python, 
Open a File in Python,  
Reading a File, 
Writing to a File 
Python seek() function,  
Python tell() function
Conclusions
FAQs
References 

Chapter 6: Basics of File Handling in Python

File handling is a core feature of Python that allows us to create, read, write, and manipulate files directly. Understanding these basics is essential for working with persistent data and storing information outside of your program. This chapter delves into file operations, including opening files, reading, writing, and utilizing useful methods like seek() and tell().


6.1 Basics of File Handling in Python

Files are used to store data permanently. Python simplifies file operations with built-in functions and supports two types of file handling:

  • Text files (e.g., .txt files): Contain human-readable text.
  • Binary files (e.g., .jpg, .pdf): Store data in binary format, not human-readable.

Python uses the built-in open() function to interact with files. File handling involves the following key steps:

  1. Opening the file (using open()), which prepares it for reading, writing, or appending.
  2. Performing operations (like reading or writing).
  3. Closing the file (using close()), which releases system resources.

6.2 Open a File in Python

To open a file, Python provides the open() function, which takes two arguments:

  • Filename: The name of the file to open.
  • Mode: Specifies the operation (e.g., read, write, or append).

The syntax is:

file = open(filename, mode)

Common file modes:

Mode Description
'r' Opens the file for reading (default).
'w' Opens the file for writing. Creates a new file or overwrites if it exists.
'a' Opens the file for appending. Adds data to the end of the file.
'b' Binary mode. Combine with 'r', 'w', or 'a' for binary files.
'+' Updates the file (read and write).

Example:

# Opening a file in read mode
file = open("example.txt", "r")
print(file.read())  # Reads the content of the file
file.close()        # Always close the file after use

6.3 Reading a File

Python offers several methods to read a file:

  1. read(): Reads the entire file or a specified number of characters.
  2. readline(): Reads one line at a time.
  3. readlines(): Reads all lines into a list.

Example:

# Read the entire file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

# Read line by line
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # Strip removes trailing newlines

6.4 Writing to a File

To write data to a file, use the write() or writelines() methods:

  1. write(): Writes a single string to the file.
  2. writelines(): Writes a list of strings to the file.

Example:

# Writing data to a file
with open("example.txt", "w") as file:
    file.write("This is a new line.\n")

# Appending data to a file
with open("example.txt", "a") as file:
    file.write("This is appended text.\n")

6.5 Python seek() Function

The seek() function moves the file pointer to a specific position, enabling random access to file content.

Syntax:

file.seek(offset, whence)
  • offset: The number of bytes to move.
  • whence (optional): Reference point for movement.
    • 0 (default): Beginning of the file.
    • 1: Current position.
    • 2: End of the file.

Example:

# Moving the file pointer
with open("example.txt", "r") as file:
    file.seek(10)  # Moves pointer to the 10th byte
    print(file.read())  # Reads from the new position

6.6 Python tell() Function

The tell() function returns the current position of the file pointer. This is useful for tracking where the file is being read or written.

Syntax:

position = file.tell()

Example:

# Getting the current file pointer position
with open("example.txt", "r") as file:
    print(file.tell())  # Outputs 0 (beginning of the file)
    file.read(5)
    print(file.tell())  # Outputs 5 (after reading 5 characters)

Conclusions 

File handling is a fundamental skill in Python, enabling you to work with external files effectively. This chapter covered:

  • Opening files using open().
  • Reading file content with read(), readline(), and readlines().
  • Writing to files with write() and writelines().
  • Using seek() to move the file pointer and tell() to get its current position.

Understanding these basics will help you manage files efficiently in Python programs. In the next chapter, we’ll explore error handling during file operations and working with CSV files.

References

For comprehensive information on file handling in Python, you can refer to the following resources:

Official Documentation:

The Python documentation provides a detailed guide on file handling, including opening, reading, writing, and closing files, as well as working with file paths.

W3Schools:

A popular tutorial website that offers a beginner-friendly guide to file handling in Python.

Real Python:

Provides in-depth tutorials and articles on various Python topics, including file handling.

GeeksforGeeks:

Offers a collection of articles and examples related to file handling in Python, covering different scenarios and use cases.


Comments