Python File Handling Tutorial


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.


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

# Performing file operations

# Closing the file

2. Reading Files

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


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

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

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

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.


# 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').


# 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.


import os

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

# Creating a new directory

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

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

6. Listing Files in a Directory

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


# 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.


# 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.


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.


# Creating a directory
print("Directory created successfully")

# Deleting a 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().


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

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

    # Setting the position to the beginning
    print("Reset Position:",

11. Handling File Exceptions

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


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


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.