Week 11: Interacting with Files

Learn how to read from and write to files in Python.

Explore Chapter 11

Chapter 11: Reading and Writing Files

Opening and Closing Files.

To work with files in Python, you first need to open them. After you're done with the file, it's good practice to close it to free up system resources.

The `open()` Function

The `open()` function is used to open a file. It takes two primary arguments:

  • `filename`: The name of the file you want to open.
  • `mode`: A string specifying the mode in which the file should be opened.

Common file modes:

  • `'r'`: Read mode (default). Opens the file for reading.
  • `'w'`: Write mode. Opens the file for writing. If the file exists, its contents are overwritten. If the file doesn't exist, it creates a new file.
  • `'a'`: Append mode. Opens the file for writing, but new data is appended to the end of the file. If the file doesn't exist, it creates a new file.
  • `'b'`: Binary mode. Used to open files in binary format (e.g., images, audio files).
  • `'+'`: Update mode. Used for both reading and writing.
# Opening a file in read mode
file = open("my_file.txt", "r")

# Opening a file in write mode
file = open("output.txt", "w")

# Opening a file in append mode
file = open("log.txt", "a")

The `close()` Method

The `close()` method is used to close an open file. It's important to close files after you're done with them to release any resources held by the file handle.

file = open("my_file.txt", "r")
# ... do some file operations ...
file.close()

If you forget to close a file, Python will eventually close it automatically when the program exits, but it's best to be explicit and close them yourself.

Reading from Files.

Python provides several methods for reading data from a file.

`read()` Method

The `read()` method reads the entire contents of the file as a single string.

file = open("my_file.txt", "r")
content = file.read()
print(content)
file.close()

`readline()` Method

The `readline()` method reads a single line from the file, including the newline character (`\n`) at the end.

file = open("my_file.txt", "r")
line1 = file.readline()
line2 = file.readline()
print("First line:", line1)
print("Second line:", line2)
file.close()

`readlines()` Method

The `readlines()` method reads all lines from the file and returns them as a list of strings.

file = open("my_file.txt", "r")
lines = file.readlines()
for line in lines:
    print(line.strip()) # strip() removes leading/trailing whitespace, including \n
file.close()

Iterating Through Lines

A common and efficient way to read a file line by line is to iterate directly over the file object in a `for` loop.

file = open("my_file.txt", "r")
for line in file:
    print(line.strip())
file.close()

Writing to Files.

You can also write data to files using Python.

`write()` Method

The `write()` method writes a string to the file. It does not automatically add a newline character, so you need to include `\n` explicitly if you want to start a new line.

file = open("output.txt", "w")
file.write("Hello, world!\n")
file.write("This is a new line.\n")
file.close()

If you open a file in `'w'` mode and the file already exists, its contents will be overwritten. If you want to append to an existing file, use `'a'` mode.

`writelines()` Method

The `writelines()` method writes a list of strings to the file.

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open("output.txt", "w")
file.writelines(lines)
file.close()

Using the `with` Statement for Automatic File Handling.

The `with` statement provides a more convenient and safer way to work with files. It automatically takes care of closing the file, even if exceptions occur.

Syntax

with open("filename", "mode") as file:
    # Code to work with the file
    # ...
# The file is automatically closed outside the with block

The `with` statement creates a context in which the file is open. Once the `with` block finishes (either normally or due to an exception), the file is automatically closed.

Examples

# Reading from a file using with
with open("my_file.txt", "r") as file:
    for line in file:
        print(line.strip())

# Writing to a file using with
with open("output.txt", "w") as file:
    file.write("This is written using with.\n")

# Appending to a file using with
with open("log.txt", "a") as file:
    file.write("New log entry.\n")

Using the `with` statement is highly recommended as it makes your code cleaner and less prone to errors related to file handling.

Syllabus