Welcome back! Yesterday, we learned about modules and packages in Python. Today, we’ll dive into working with files, which is essential for reading from and writing to files in your programs. By the end of this day, you’ll know how to handle files in Python. Let’s get started!
Reading Files
To read from a file, you can use the open() function. Here’s the basic syntax:
file = open("filename.txt", "r")
content = file.read()
file.close()
print(content)
You can also use the with statement to automatically close the file after reading:
with open("filename.txt", "r") as file:
content = file.read()
print(content)
Writing Files
To write to a file, you can use the open() function with the "w" (write) mode. If the file doesn’t exist, it will be created. If it does exist, its content will be overwritten.
with open("filename.txt", "w") as file:
file.write("Hello, World!")
To append to a file, use the "a" (append) mode:
with open("filename.txt", "a") as file:
file.write("\nThis is a new line.")
Reading and Writing Lines
You can read and write files line by line using the readlines() and writelines() methods.
Example:
# Writing lines to a file
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("filename.txt", "w") as file:
file.writelines(lines)
# Reading lines from a file
with open("filename.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
Handling File Paths
You can use the os module to handle file paths. This is useful when working with files across different operating systems.
Example:
import os
file_path = os.path.join("folder", "filename.txt")
with open(file_path, "w") as file:
file.write("Hello from a nested folder!")
Practice Time!
Let’s put what we’ve learned into practice. Write a Python program that reads from a file, writes to a file, and appends to a file.
Create a text file named data.txt with the following content:
This is the first line.
This is the second line.
This is the third line.
Write a Python program to read the content of data.txt, print it, and then write and append new content to the file.
# Reading from a file
with open("data.txt", "r") as file:
content = file.read()
print("Content of data.txt:")
print(content)
# Writing to a file
with open("data.txt", "w") as file:
file.write("This is a new first line.\n")
# Appending to a file
with open("data.txt", "a") as file:
file.write("This is appended to the file.\n")
# Reading the updated content
with open("data.txt", "r") as file:
updated_content = file.read()
print("Updated content of data.txt:")
print(updated_content)
Conclusion
Great job today! You’ve learned how to read from and write to files in Python, which is crucial for handling data in your programs. Tomorrow, we’ll dive into lists and list comprehensions, which are powerful tools for working with collections of data. Keep practicing and having fun coding!
Leave a Reply