Writing Data to Files in Python
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Writing Data to Files in Python

Kishore V


Writing Data to Files in Python

Python makes it easy to write data into files. Depending on the mode you choose, you can add new content, replace existing content, or create a brand-new file.

Writing to an Existing File

When writing to an already available file, you must specify the correct file mode in the open() function.

Common Write Modes

  • "a" → Append mode: Adds new data to the end of the file without removing existing content.
  • "w" → Write mode: Clears the file and writes fresh content from the beginning.

Example: Appending Content to a File

First, we append content. Then, we read it back to verify the changes.

Initial log entry. New entry added successfully.

Overwriting Existing File Content

To completely replace the contents of a file, use write mode ("w").

Example: Replace File Data

This file has been reset.

Important:

Opening a file in "w" mode removes all previous content before writing new data.

Creating New Files in Python

Python can also create files during the writing process. The behavior depends on the mode used.

File Creation Modes

  • "x" → Creates a new file and raises an error if it already exists
  • "a" → Creates the file if it does not exist
  • "w" → Creates the file if it does not exist

Example: Create a New File

report.txt created successfully.

Our website uses cookies to enhance your experience. Learn More
Accept !