Reading and Writing Files

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will learn how to read and write files in Python. We will start with simple examples and gradually increase the complexity of the code.

Reading and writing files is an essential skill in any programming language. It allows us to store and manipulate data in a persistent manner, and is a key building block for many applications.
In Python, reading and writing files is straightforward and easy to learn. We will start by learning how to read a file, and then move on to writing files.

Achievements

  • Reading and Writing Files

Reading a File

To read a file in Python, we use the open function, which returns a file object. We can then use various methods of the file object to read the contents of the file.

Open up a new Python interpreter session and type the following code:

python3

Here is an example of how to open and read a text file:

## Open the file
f = open('filename.txt', 'r')

## Read the contents of the file
contents = f.read()

## Print the contents
print(contents)

## Close the file
f.close()

The open function takes two arguments: the name of the file, and the mode in which to open the file. In this case, we use the 'r' mode, which stands for "read". This is the default mode, so we could also have written open('filename.txt').

The read method of the file object returns the contents of the file as a string. We can then print the contents or manipulate them in any way we like.

It is important to close the file when we are done with it, to free up system resources. We can do this using the close method of the file object.

Writing a File

To write to a file in Python, we follow a similar process to reading a file. We use the open function to obtain a file object, and then use the write method to write to the file.

Here is an example of how to open a file for writing and write some text to it:

## Open the file
f = open('filename.txt', 'w')

## Write some text to the file
f.write('Hello, world!\nPython')

## Close the file
f.close()

As with reading a file, we use the open function to obtain a file object. This time, we use the 'w' mode, which stands for "write". This will create the file if it does not already exist, and overwrite it if it does.

The write method takes a string as an argument and writes it to the file. As with reading a file, it is important to close the file when we are done with it.

Working with File Contents

Now that we know how to read and write files, let's look at some more advanced examples of working with file contents.

Reading a file line by line

Sometimes, we may want to read a file line by line, rather than reading the entire contents at once. To do this, we can use the readline method of the file object.
Here is an example of how to read a file line by line:

## Open the file
f = open('filename.txt', 'r')

## Read and print each line
for line in f:
    print(line)

## Close the file
f.close()

The for loop iterates over the lines of the file. On each iteration, it reads and prints the current line. When there are no more lines to read, the loop ends and the file is closed.

Writing to a file line by line

To write to a file line by line, we can use the writelines method of the file object. This method takes a list of strings as an argument and writes them to the file, with each string in the list becoming a separate line in the file.

Here is an example of how to write to a file line by line:

## Open the file
f = open('filename.txt', 'w')

## Write a list of lines to the file
lines = ['Line 1', 'Line 2', 'Line 3']
f.writelines(lines)

## Close the file
f.close()

Appending to a file

To append to a file, rather than overwriting it, we can use the 'a' mode when opening the file. This will open the file in append mode, allowing us to add new content to the end of the file without overwriting the existing content.

Here is an example of how to append to a file:

## Open the file
f = open('filename.txt', 'a')

## Append some text to the file
f.write('This is new content')

## Close the file
f.close()

with Statement

The with statement in Python is used to wrap the execution of a block of code with methods defined by a context manager. A context manager is an object that defines the methods __enter__ and __exit__. The with statement creates a temporary context manager for the duration of the indented block of code that follows it.

The open function is a built-in Python function that returns a file object, which represents an open file. When working with files, it is important to close them when we are finished with them to free up system resources. The with statement makes it easier to work with files, because it automatically closes the file when the block of code is exited, even if an exception is raised.

Here is an example of how to use the with statement to open and read a file:

with open('filename.txt', 'r') as f:
    contents = f.read()
    print(contents)

In this example, the open function is called within the with statement to open the file 'filename.txt' in read mode. The file object is then passed to the as clause, where it is given the name f. The indented block of code that follows the with statement can then use the file object f to read the contents of the file.

When the block of code is exited, the file is automatically closed by the context manager, even if an exception is raised. This means that we don't have to call the close method of the file object explicitly.

Using the with statement to manage the lifetime of a file object is recommended over manually opening and closing the file, because it is more concise and ensures that the file is always properly closed, even if an exception is raised.

Summary

In this lab, we learned how to read and write files in Python. We saw how to open and close files, read and write their contents, and work with file contents in more advanced ways. We also saw how to use different modes when opening files to control how they are accessed.

By the end of this lab, you should be able to read and write files in Python with confidence.

Other Python Tutorials you may like