How to write to a file?

To write to a file in Python, you can use the following code:

Writing to a New File

with open('output_file.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new file.")

Appending to an Existing File

If you want to add content to an existing file without overwriting it, use the append mode ('a'):

with open('output_file.txt', 'a') as file:
    file.write("\nThis line will be added to the end of the file.")

Explanation:

  • 'w': Opens the file for writing (creates a new file or truncates an existing file).
  • 'a': Opens the file for appending (creates a new file if it doesn't exist).

Feel free to ask if you have more questions!

0 Comments

no data
Be the first to share your comment!