Python Tutorial: Append Files 📝

beginner
13 min

Python Tutorial: Append Files 📝

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!

Understanding File Operations 🎯

Before we delve into appending files, let's first understand some fundamental Python concepts about working with files.

Opening a File 📝

python
file = open('example.txt', 'r') # 'r' stands for reading mode

Reading a File 📝

python
content = file.read() print(content) file.close() # Always remember to close the file after use!

Appending to a File 🎯

Now that we've covered the basics, let's move on to the main topic: appending to a file.

Opening a File for Appending 📝

To append data to a file, we open the file in 'a' (append) mode.

python
file = open('example.txt', 'a')

Writing to a File 🎯

We can use the write() function to write data to a file.

python
file.write('Hello, World! 🎉') file.close()

Now, if you open the example.txt file, you'll see the following content:

(Initial content) Hello, World! 🎉

Real-world Example 🎯

Let's consider a real-world scenario where we want to keep a log of user activities on a website.

python
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.

Quiz 🎯

Quick Quiz
Question 1 of 1

Which mode is used to append data to a file in Python?

Happy coding! 🚀