Introduction

Reading and writing files is a common task in Python, allowing you to interact with external data sources and store information for later use. In this guide, we'll explore how to read from and write to files using Python, and we'll provide sample code to demonstrate the process.


Opening and Closing Files

To read from or write to a file, you first need to open it using the open() function. Once you are done, it's essential to close the file using the close() method to release system resources.

# Opening a file for reading
file = open("example.txt", "r")
# Reading from the file
content = file.read()
print(content)
# Closing the file
file.close()

Reading Text Files

To read the contents of a text file, you can use the read() method to retrieve the entire content or readline() to read one line at a time.

# Reading the entire content of a text file
file = open("sample.txt", "r")
content = file.read()
file.close()
# Reading line by line
file = open("sample.txt", "r")
for line in file:
print(line)
file.close()

Writing to Text Files

To write to a text file, you can use the write() method, and you can specify the mode as "w" to create a new file or "a" to append to an existing one.

# Writing to a new text file
file = open("output.txt", "w")
file.write("Hello, World!\n")
file.write("This is a new line.")
file.close()
# Appending to an existing text file
file = open("output.txt", "a")
file.write("\nAppending more text.")
file.close()

Using the With Statement

Python provides the with statement for better file handling. It automatically closes the file when the block is exited.

# Using the with statement to read a file
with open("example.txt", "r") as file:
content = file.read()
# Using the with statement to write to a file
with open("output.txt", "w") as file:
file.write("Using the 'with' statement.")

Conclusion

Reading and writing files in Python is an essential skill for dealing with various data sources and creating persistent storage for your applications. Whether you're working with text files, binary data, or even CSV files, Python provides powerful and flexible tools to handle file operations efficiently.