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.
Verify the Updated Content
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
Read the File After Overwriting
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. |
