File Handling in Python: A Complete Guide | FACE Prep

File Handling in Python: A Complete Guide | FACE Prep

Complete Guide to File Handling in Python: Read, Write, Delete & More

In Python programming, file handling refers to the process of creating, reading, writing, closing, and deleting files. Files are essential for storing data permanently on secondary storage devices like hard drives. Python makes file handling incredibly simple, unlike other programming languages where it can often be complex and cumbersome. Whether you are dealing with plain text files or complex data files like CSV and Excel, Python offers efficient tools for managing them.This guide will walk you through the essential steps of file handling in Python, covering how to open, write, read, close, and delete files with examples and helpful visuals.

Why is File Handling Important in Python?

File handling in Python is crucial for several reasons:
  • Easy Data Management: Python makes it straightforward to store and manipulate data.
  • Automating Repetitive Tasks: With Python file handling, you can automate tasks like adding entries to files (e.g., updating passwords or logs) without manual intervention.
  • Data Persistence: You need file handling when you want to save data between sessions, such as reading and writing user inputs, log data, or configuration settings.
Other programming languages have file handling, but Python’s syntax is user-friendly and compact, making it ideal for beginners and professionals alike.

How to Open a Text File in Python

Before working with any file in Python, the first step is opening the file. Python provides the built-in function open() to open files in different modes like read, write, append, etc.

Example: Opening a File for Writing

Let’s assume you have a text file named PassCred.txt where you store passwords. To open this file for writing, you can use the following code:
python
# Open a file for writing (creates the file if it doesn't exist) f = open("PassCred.txt", "w")
In this case, f is the file object that allows reading or writing to the file. The mode "w" stands for write mode. If the file doesn’t exist, Python will create it for you. 

How to Write to a Text File in Python

Once you have opened a file, you can write data to it using the write() function. This function writes a string to the file.

Example: Writing a String to a File

python
# Open the file in write mode and write a string to it f = open("PassCred.txt", "w") f.write("FACE Prep")
After executing the code above, the string “FACE Prep” will be written into PassCred.txt.

Example: Writing Multiple Lines to a File

If you need to write multiple lines to a file, use the writelines() function.
python
# Write multiple lines into the file lines = ['Learn Python\n', 'Master File Handling\n', 'FACE Prep\n'] f.writelines(lines)
 

How to Read from a Text File in Python

After writing to a file, you may want to read the data back. Python offers several methods for reading file contents, such as read(), readline(), and readlines().

Example: Reading Entire File

python
# Open the file in read mode and print its content f = open("PassCred.txt", "r") print(f.read())
This will display the entire content of PassCred.txt.

Example: Reading Specific Number of Characters

python
# Read the first 4 characters f = open("PassCred.txt", "r") print(f.read(4))
This will print the first 4 characters from the file.

Example: Reading Line by Line

python
# Read the first line f = open("PassCred.txt", "r") print(f.readline())
You can call readline() multiple times to read subsequent lines from the file. 

How to Close a Text File in Python

After performing operations like reading or writing, it’s important to close the file to free up system resources. You can use the close() function for this.

Example: Closing a File

python
# Close the file after reading or writing f = open("PassCred.txt", "r") f.close()
You can check if the file is closed using the closed() function.
python
# Check if the file is closed f = open("PassCred.txt", "r") f.close() print(f.closed) # Outputs True if the file is closed
 

How to Delete a Text File in Python

Python allows you to delete files from your system using the remove() function, which is part of the built-in os module.

Example: Deleting a File

python
from os import remove# Remove the file remove(“PassCred.txt”)
Once the file is deleted, it will be permanently removed from your system (and won’t go to the recycle bin). 

Frequently Asked Questions (FAQs)

1. What is file handling in Python?

File handling in Python involves operations like creating, reading, writing, closing, and deleting files, providing a way to interact with files stored on a computer.

2. How to append data to an existing file?

To append data to an existing file, use the "a" mode (append mode) when opening the file. Here’s an example:
python
# Append data to the file f = open("PassCred.txt", "a") f.write("New Password\n")
This will add the string “New Password” to the end of the file without overwriting existing content.

Conclusion

Mastering file handling in Python is an essential skill for developers working with persistent data. Python’s simplicity makes it an ideal choice for file manipulation tasks, whether you’re working with text, CSV, or other formats. By learning how to open, write, read, close, and delete files, you’ll be equipped to handle real-world data storage tasks with ease.  
c