Skip to content

Computer Science · Ch 2 — File Handling in Python

Writing to a Text File

2.4

Writing to a Text File

To write data into a file, you must first open it in either write mode ('w') or append mode ('a'). If you open an existing file in write mode, its previous contents are erased and the file object is positioned at the very beginning of the file, ready to write fresh content from the start. If you open it in append mode instead, the existing data is preserved and the file object is placed at the end of the file, so anything you write lands after what is already there — nothing is lost.

Once the file is open in the correct mode, Python gives you two methods to actually write data into it:

  • write() — for writing a single string to the file.
  • writelines() — for writing a sequence of strings (like a list or tuple) to the file. …