Skip to Content
Course content

6.1 Reading and Writing Files

In Python, working with files is a common task, especially when you need to store data persistently or interact with external data sources. Python provides a built-in library called open() for file handling, which allows you to read from, write to, and manipulate files. Below, we will explain how to read and write files using various modes, along with common file handling operations.

1. Opening a File

To open a file in Python, you use the built-in open() function. This function requires at least one argument: the name of the file you want to open. The open() function also accepts a second argument called the mode, which specifies whether you want to read, write, or append data to the file.

Syntax of open():

file = open("filename.txt", "mode")

File Modes:

  • r: Read (default mode). Opens the file for reading. If the file does not exist, an error will occur.
  • w: Write. Opens the file for writing. If the file already exists, it will overwrite it. If the file does not exist, it creates a new one.
  • a: Append. Opens the file for appending data. If the file does not exist, it creates a new one.
  • rb: Read in binary mode.
  • wb: Write in binary mode.

Example:

# Open a file in write mode
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()  # Don't forget to close the file after writing

2. Reading from Files

Once a file is opened in the appropriate mode, you can read the contents using various methods. Some of the most common methods are:

  • read(): Reads the entire content of the file.
  • readline(): Reads one line at a time.
  • readlines(): Reads the file and returns a list of lines.

Example: Reading the entire content of a file

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

Example: Reading line by line

file = open("example.txt", "r")
line = file.readline()
while line:
    print(line, end='')  # Print each line without adding extra newline
    line = file.readline()
file.close()

Example: Reading all lines into a list

file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
    print(line, end='')
file.close()

3. Writing to Files

You can write to files using the write() method. If the file is opened in write (w) mode, it will overwrite the file, while in append (a) mode, it will add new content at the end of the file.

Example: Writing a string to a file

file = open("output.txt", "w")
file.write("This is a new line.")
file.close()

Example: Appending content to a file

file = open("output.txt", "a")
file.write("\nThis is an appended line.")
file.close()

4. Using with Statement for File Handling

In Python, it is highly recommended to use the with statement when working with files. This is because it automatically handles the closing of the file, even if an exception occurs during file operations.

Example: Reading using the with statement

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

Example: Writing using the with statement

with open("output.txt", "w") as file:
    file.write("Writing to file with 'with' statement.")

The advantage of the with statement is that it ensures the file is closed as soon as the block of code is executed, which is important to avoid resource leaks and improve code safety.

5. Handling File Exceptions

When working with files, there are certain scenarios where things might go wrong (e.g., file not found, permission issues, etc.). It is a good practice to handle these exceptions using try and except blocks.

Example: Handling exceptions

try:
    with open("nonexistent_file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file was not found.")
except PermissionError:
    print("You do not have permission to access this file.")

6. File Closing

It’s important to close the file after you’re done with it to free up system resources. If you don’t use the with statement (which automatically closes the file), you must call the close() method manually.

Example: Manually closing the file

file = open("example.txt", "r")
content = file.read()
file.close()  # Explicitly close the file

7. File Paths

When opening a file, you can specify the absolute path or relative path.

  • Absolute path: The complete path from the root directory to the file (e.g., C:/Users/John/example.txt).
  • Relative path: The path relative to the current working directory (e.g., ./example.txt).

Example: Using absolute and relative paths

# Using an absolute path
file = open("C:/Users/John/example.txt", "r")
content = file.read()
file.close()

# Using a relative path
file = open("./example.txt", "r")
content = file.read()
file.close()

Summary of File Handling Methods:

Method Description
open(filename, mode) Opens a file in the specified mode (read/write/append).
read() Reads the entire content of the file.
readline() Reads one line from the file.
readlines() Reads all lines of the file into a list.
write() Writes content to the file.
close() Closes the file.
with open() as A context manager for automatic file closing.

Conclusion:

  • Reading and writing files in Python is simple and straightforward using the open() function.
  • Always use the with statement to handle files, as it ensures proper resource management.
  • Handle exceptions properly to ensure the program can deal with missing files or permission issues.

Commenting is not enabled on this course.