Opening and Closing Files

Before you can read or write to a file, you need to open it using the built-in open() function. This function returns a file object that provides methods for interacting with the file.

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

The open() function takes two arguments: the file path (relative or absolute) and the mode in which the file should be opened. The mode can be one of the following:

  • "r" (read mode, default)
  • "w" (write mode, creates a new file or overwrites an existing one)
  • "a" (append mode, adds new content to the end of the file)
  • "x" (exclusive creation mode, creates a new file but fails if the file already exists)

It's important to close the file after you're done with it to free up system resources. Alternatively, you can use the with statement, which automatically closes the file when the code block is exited.

with open("example.txt", "r") as file:
# Perform file operations
contents = file.read()

Reading from Files

Once you've opened a file in read mode, you can use various methods to read its contents:

  • read(): Reads the entire contents of the file as a string.
  • readline(): Reads one line from the file.
  • readlines(): Reads all lines from the file and returns them as a list of strings.
with open("example.txt", "r") as file:
contents = file.read()
print(contents)

file.seek(0)  # Move the file pointer back to the beginning
lines = file.readlines()
print(lines)

Writing to Files

To write data to a file, you need to open it in write mode ("w") or append mode ("a").

  • write(): Writes a string to the file.
  • writelines(): Writes a list of strings to the file.
with open("example.txt", "w") as file:
file.write("This is a new line.\n")
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)

File Modes

Besides the basic read, write, and append modes, Python also supports other file modes:

  • "r+": Read and write mode (file must exist)
  • "w+": Read and write mode (creates a new file or overwrites an existing one)
  • "a+": Read and append mode (creates a new file if it doesn't exist)
  • "b": Binary mode (can be combined with other modes, e.g., "rb", "wb")

File Pointer

The file pointer is a cursor that keeps track of the current position in the file during read/write operations. You can use the seek() method to move the file pointer to a specific position in the file.

with open("example.txt", "r") as file:
data = file.read(10)  # Read the first 10 characters
print(data)

file.seek(0)  # Move the file pointer back to the beginning
contents = file.read()  # Read the entire file
print(contents)

Context Manager (with statement)

As mentioned earlier, the with statement is recommended when working with files. It automatically takes care of opening and closing the file, even if an exception occurs, ensuring proper resource management.

try:
with open("example.txt", "r") as file:
    contents = file.read()
    # Perform operations on contents
except FileNotFoundError:
print("File not found.")

In the next chapter, we'll explore Object-Oriented Programming (OOP) in Python, which is a powerful programming paradigm that allows you to create and work with classes and objects.