Can I write to a file?

QuestionsQuestions8 SkillsProYour First Python LabOct, 08 2025
0106

Yes, you can write to a file in Python using the built-in open() function along with the write() method. Here's a simple example:

# Open a file in write mode
with open('example.txt', 'w') as file:
    file.write("Hello, world!\n")
    file.write("This is a new line.")

# The file is automatically closed after the with block

In this example:

  • The open() function is used to create or open a file named example.txt in write mode ('w').
  • The write() method writes the specified string to the file.
  • Using the with statement ensures that the file is properly closed after writing, even if an error occurs.

You can also append to a file by using the append mode ('a'):

# Open a file in append mode
with open('example.txt', 'a') as file:
    file.write("\nThis line will be appended.")

This will add a new line to the end of example.txt without overwriting the existing content.

0 Comments

no data
Be the first to share your comment!