python
  1. python-reading-and-writing-files

Python Reading and Writing Files

Python provides different functions for working with files. In this tutorial, we will learn about reading and writing files in Python.

Reading Files

Python allows us to read the contents of a file using the open() function. The open() function returns a file object that we can use to read the file.

Syntax:

file = open(filename, mode)

Here, the filename parameter is the name of the file we want to open. The mode parameter is optional and it specifies the mode in which we want to open the file.

Example:

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

This code opens the file named sample.txt in read mode (r). Now, we can read the contents of the file using the read() method.

Output:

The read() method returns the contents of the file as a string.

Example:

file = open("sample.txt", "r")
contents = file.read()
print(contents)

Explanation:

In the above example, we have opened the file sample.txt and read its contents using the read() method. The contents of the file are stored in the contents variable. Finally, we have printed the contents of the file on the console using the print() function.

Writing Files

Python also allows us to write to a file using the open() function. We just need to specify the mode as w (write) or a (append) instead of r (read).

Syntax:

file = open(filename, mode)

Here, the filename parameter is the name of the file we want to create or open. The mode parameter is optional and it specifies the mode in which we want to open the file.

Example:

file = open("output.txt", "w")
file.write("Hello, world!")
file.close()

In the above code, we have opened a file named output.txt in write mode (w). We have written the string "Hello, world!" to the file using the write() method and closed the file using the close() method.

Output:

The write() method does not return any value. It just writes the specified string to the file.

Important Points

  • When we open a file using the open() function, we should always close it using the close() method to free up system resources.
  • If the file does not exist, it will be created when we open it in write mode (w).
  • If we open a file in append mode (a), the contents will be appended to the end of the file.

Summary

We have learned how to read and write files in Python using the open() function. We have also learned about the different modes in which we can open a file and how to close a file after we are done with it.

Published on: