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.
Overwriting Existing File Content
To completely replace the contents of a file, use write mode
("w").
Example: Replace File Data
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
