This tutorial aims to explore how to read and write text files in Python. Handling text files is an essential skill for any programmer as it allows you to store, access, and manipulate data. In Python, the built-in open()
function is used to perform file handling tasks.
By the end of this tutorial, you will learn:
Prerequisites: Basic knowledge of Python programming is required to follow this tutorial.
In Python, we use the open()
function to open a file. Its syntax is as follows:
open("filename", "mode")
The mode parameter defines the type of action you want to perform on the file. Here are some common modes:
To read the entire content of a file, we use the read()
method.
file.read()
To write data to a file, we use the write()
method.
file.write("Your text goes here")
Always remember to close the file after you are done with it using the close()
method.
file.close()
# Open the file in read mode
file = open("sample.txt", "r")
# Read the entire file content
content = file.read()
# Close the file
file.close()
# Print the content
print(content)
Here, we first open the file "sample.txt" in read mode. Then, we read the entire content of the file using read()
, close the file using close()
, and finally print the content.
# Open the file in write mode
file = open("sample.txt", "w")
# Write to the file
file.write("Hello, world!")
# Close the file
file.close()
In this example, we open the file in write mode, write "Hello, world!" to it, and then close it.
In this tutorial, we learned how to read and write text files in Python. We explored the open()
function and the various modes in which a file can be opened. We learned how to read the content of a file using read()
and write to a file using write()
. We also saw the importance of closing a file after operations using close()
.
For further learning, consider exploring other file operations in Python like seeking, reading line by line, and working with binary files.
Solutions and further practice exercises can be found here.