Welcome to our comprehensive guide on appending files in Python! This tutorial is designed for both beginners and intermediates, covering the basics and delving into advanced examples. Let's dive in!
Before we delve into appending files, let's first understand some fundamental Python concepts about working with files.
file = open('example.txt', 'r') # 'r' stands for reading modecontent = file.read()
print(content)
file.close() # Always remember to close the file after use!Now that we've covered the basics, let's move on to the main topic: appending to a file.
To append data to a file, we open the file in 'a' (append) mode.
file = open('example.txt', 'a')We can use the write() function to write data to a file.
file.write('Hello, World! 🎉')
file.close()Now, if you open the example.txt file, you'll see the following content:
(Initial content)
Hello, World! 🎉
Let's consider a real-world scenario where we want to keep a log of user activities on a website.
import datetime
def log_activity(activity):
now = datetime.datetime.now()
with open('activity_log.txt', 'a') as file:
file.write(f'{now} - {activity}\n')
# Logging an activity
log_activity('User logged in.')
log_activity('User visited the homepage.')Now, when you open the activity_log.txt file, you'll see something like:
(Initial content)
2022-03-01 12:34:56 - User logged in.
2022-03-01 12:35:02 - User visited the homepage.
Which mode is used to append data to a file in Python?
Happy coding! 🚀