Python File Handling Tutorial

Introduction

File handling is an essential aspect of programming, allowing you to read from and write to files. Python provides built-in functions and methods to handle files, making it easy to perform various file operations. This tutorial covers the basics of file handling in Python, including opening, reading, writing, appending, and closing files, as well as handling exceptions during file operations. Additionally, it covers listing files, renaming files, copying files, creating directories, and deleting directories.

Table of Contents

  1. Opening and Closing Files
  2. Reading Files
  3. Writing Files
  4. Appending to Files
  5. Working with File Paths
  6. Listing Files in a Directory
  7. Renaming Files
  8. Copying Files
  9. Creating and Deleting Directories
  10. File Methods
  11. Handling File Exceptions
  12. Conclusion

1. Opening and Closing Files

Opening a File

To open a file, use the open() function, which returns a file object. The open() function takes two arguments: the file name and the mode in which the file should be opened.

Common modes:

  • 'r': Read (default mode)
  • 'w': Write (creates a new file or truncates an existing file)
  • 'a': Append (adds content to the end of the file)
  • 'b': Binary mode (e.g., 'rb', 'wb')

Closing a File

Always close a file after completing operations to free up system resources. Use the close() method.

Example

# Opening a file in read mode
file = open("example.txt", "r")

# Performing file operations

# Closing the file
file.close()

2. Reading Files

You can read the contents of a file using various methods: read(), readline(), and readlines().

Example

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

# Reading a single line
with open("example.txt", "r") as file:
    line = file.readline()
    print(line)

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

3. Writing Files

To write to a file, open it in write mode ('w'). If the file exists, its content is truncated. If it doesn't exist, a new file is created.

Example

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

4. Appending to Files

To append content to an existing file, open it in append mode ('a').

Example

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

5. Working with File Paths

Use the os and os.path modules to work with file paths. This is useful for creating, deleting, and navigating directories and files.

Example

import os

# Getting the current working directory
current_directory = os.getcwd()
print("Current Directory:", current_directory)

# Creating a new directory
os.mkdir("new_directory")

# Changing the current working directory
os.chdir("new_directory")
print("New Directory:", os.getcwd())

# Removing the directory
os.chdir("..")  # Move back to the parent directory
os.rmdir("new_directory")

6. Listing Files in a Directory

You can list all files in a directory using the os.listdir() method.

Example

# Listing files in the current directory
files = os.listdir()
print("Files in the current directory:", files)

# Listing files in a specific directory
specific_files = os.listdir("path/to/directory")
print("Files in the specified directory:", specific_files)

7. Renaming Files

You can rename a file using the os.rename() method.

Example

# Renaming a file
os.rename("example.txt", "renamed_example.txt")
print("File renamed successfully")

8. Copying Files

You can copy files using the shutil module.

Example

import shutil

# Copying a file
shutil.copy("renamed_example.txt", "copied_example.txt")
print("File copied successfully")

9. Creating and Deleting Directories

You can create and delete directories using the os module.

Example

# Creating a directory
os.mkdir("test_directory")
print("Directory created successfully")

# Deleting a directory
os.rmdir("test_directory")
print("Directory deleted successfully")

10. File Methods

Python provides several built-in methods for file objects, such as write(), read(), close(), seek(), and tell().

Example

# Using tell() and seek() methods
with open("copied_example.txt", "r") as file:
    # Reading the first 5 characters
    print(file.read(5))

    # Getting the current position
    position = file.tell()
    print("Current Position:", position)

    # Setting the position to the beginning
    file.seek(0)
    print("Reset Position:", file.read(5))

11. Handling File Exceptions

Use try-except blocks to handle exceptions that may occur during file operations.

Example

try:
    with open("non_existent_file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file does not exist")
except IOError:
    print("An IOError occurred")

Conclusion

File handling in Python is an essential skill for managing data stored in files. By understanding how to open, read, write, append, and close files, as well as handle exceptions and work with file paths, you can efficiently manage files in your Python programs. Additionally, learning how to list files, rename files, copy files, create directories, and delete directories expands your ability to handle various file system operations. This tutorial covered the basics of file handling with examples to help you get started.

Comments