File Handling in Python

File handling is an essential part of any programming language. Python provides several built-in functions to create, read, write, and delete files. The main functions used for file handling are open(), read(), write(), and close().

Opening a File

You can open a file using the open() function. It returns a file object and takes two arguments: the filename and the mode (e.g., read, write, append).

Python
# Open a file for reading
file = open("example.txt", "r")  # "r" mode is for reading

# Always remember to close the file
file.close()

It’s important to always close the file after you’re done with it to free up system resources. Python provides a better way to handle this using the with statement, which automatically closes the file after the block of code is executed.

Python
# Using "with" to open a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# No need to explicitly close the file here

File Modes

When opening a file, you can specify the mode, which determines the operations you can perform on the file:

Reading from a File

Once a file is opened in read mode ("r"), you can use various methods to read its content:

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

# Reading line by line
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes the trailing newline character

# Reading all lines into a list
with open("example.txt", "r") as file:
    lines = file.readlines()
    print(lines)

Writing to a File

To write to a file, open it in write ("w"), append ("a"), or read-write ("r+") mode. The write() method writes a string to the file, while the writelines() method writes a list of strings.

Python
# Writing to a file (overwrites existing content)
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.\n")

# Appending to a file
with open("example.txt", "a") as file:
    file.write("Appending another line.\n")

# Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
    file.writelines(lines)

Closing a File

While using with handles file closing automatically, if you open a file manually, you should always close it using the close() method:

Python
file = open("example.txt", "r")
# Perform file operations
file.close()

Deleting a File

To delete a file, you can use the os module’s remove() function:

Python
import os

# Deleting a file
if os.path.exists("example.txt"):
    os.remove("example.txt")
else:
    print("The file does not exist")

If you need to delete an entire directory, use the rmdir() function from the os module. However, rmdir() only removes an empty directory. To remove a directory with content, use the shutil module:

Python
import shutil

# Deleting a directory and its contents
shutil.rmtree("my_directory")

Best Practices for File Handling

Here are some best practices to follow when working with files in Python:

By understanding and following these file handling techniques and best practices, you can efficiently manage files in your Python programs.