How do you append data to an existing file in Python?

How do you append data to an existing file in Python?

a) By opening the file in append mode using the ‘a’ mode and writing data to it
b) By opening the file in write mode using the ‘w’ mode and writing data to it
c) By opening the file in read mode using the ‘r’ mode and writing data to it
d) By using the os.append() function

Answer:

a) By opening the file in append mode using the ‘a’ mode and writing data to it

Explanation:

To append data to an existing file in Python, you open the file in append mode using the 'a' mode in the open() function. This mode allows you to add data to the end of the file without overwriting its existing content.

# Example of appending data to a file
with open("example.txt", "a") as file:
    file.write("This is additional content.")

In this example, the file example.txt is opened in append mode, and the string “This is additional content.” is added to the end of the file.

Appending data is useful when you need to add new information to a log file, update records, or continue writing to a file without losing the existing data.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top