Python Documentation

File Handling

File Handling in Python

File handling is an important part of any programming language. Python has several functions for creating, reading, updating, and deleting files.

Opening a File

To open a file, use the open() function. It takes two parameters: filename and mode.

file = open("example.txt", "r")

There are four different modes for opening a file:

  • "r" - Read - Default value. Opens a file for reading, error if the file does not exist
  • "a" - Append - Opens a file for appending, creates the file if it does not exist
  • "w" - Write - Opens a file for writing, creates the file if it does not exist
  • "x" - Create - Creates the specified file, returns an error if the file exists

Reading Files

There are several methods to read files in Python:

with open("example.txt", "r") as file:
ㅤㅤ# Read entire file
ㅤㅤcontent = file.read()
ㅤㅤ
ㅤㅤ# Read line by line
ㅤㅤfor line in file:
ㅤㅤㅤㅤprint(line)
ㅤㅤ
ㅤㅤ# Read specific number of characters
ㅤㅤcharacters = file.read(5)

Writing to Files

To write to a file, you need to open it in write mode:

with open("example.txt", "w") as file:
ㅤㅤfile.write("Hello, World!")
ㅤㅤfile.writelines(["\nThis is a new line", "\nAnd another one"])

Appending to Files

To append to a file, open it in append mode:

with open("example.txt", "a") as file:
ㅤㅤfile.write("\nThis line is appended")

Closing Files

It's important to close files when you're done with them. Using the with statement automatically closes the file when you're done:

with open("example.txt", "r") as file:
ㅤㅤcontent = file.read()
ㅤㅤprint(content)
# File is automatically closed when the 'with' block ends

When you use the with statement, Python takes care of closing the file for you, even if an exception occurs while the file is open. This is called context management and is the recommended way to handle file operations in Python.

Error Handling

When working with files, it's important to handle potential errors. Here's an example of how to use try-except blocks for error handling:

try:
ㅤㅤwith open("nonexistent_file.txt", "r") as file:
ㅤㅤㅤㅤcontent = file.read()
except FileNotFoundError:
ㅤㅤprint("The file does not exist.")
except IOError:
ㅤㅤprint("An error occurred while reading the file.")

This error handling approach allows your program to gracefully handle situations where the file might not exist or other I/O errors occur, preventing your program from crashing.