Writing Data to Files in Python

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

Try it Yourself

Verify the Updated Content

Try it Yourself

Overwriting Existing File Content

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

Example: Replace File Data

Try it Yourself

Read the File After Overwriting

Try it Yourself

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

Try it Yourself

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