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 completely and writes fresh content from the beginning.

Example: Appending Content to a File

Using the "a" mode ensures we don't destroy whatever is already inside the file.

Content successfully appended!

Verify the Updated Content

Existing log entry 1... New entry added successfully.

Overwriting Existing File Content

To completely replace the contents of a file, use write mode ("w"). Important: Opening a file in "w" mode removes all previous content before writing new data. Be careful!

Example: Replace File Data

File successfully overwritten!

Read the File After Overwriting

This file has been reset.

Creating New Files in Python

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

File Creation Modes

Mode Creation Behavior
"x" Creates a new file. Raises an error if it already exists. (Safest for new files)
"a" Creates the file if it does not exist. (Great for logs)
"w" Creates the file if it does not exist.

Example: Create a New File Using Create Mode

report.txt successfully created!
Our website uses cookies to enhance your experience. Learn More
Accept !