How do you write data to a file in Python?

How do you write data to a file in Python?

a) By opening the file in write mode and using the write() method
b) By opening the file in read mode and using the write() method
c) By opening the file in append mode and using the read() method
d) By opening the file in binary mode and using the append() method

Answer:

a) By opening the file in write mode and using the write() method

Explanation:

To write data to a file in Python, you open the file in write mode using the open() function and then use the write() method to add content to the file. If the file does not exist, it will be created; if it does exist, the existing content will be overwritten.

# Example of writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, World!")

In this example, the file example.txt is opened in write mode, and the string “Hello, World!” is written to it. If the file already exists, its contents will be replaced with the new data.

Writing to a file is a common operation in many programs, especially when you need to save output, log data, or generate reports.

Leave a Comment

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

Scroll to Top