Python File Write / Create Files

Python provides powerful file handling functions using the built-in open() method and different modes for writing, appending, and creating files.

 File Modes for Writing

ModeDescription
wWrite – Creates new or overwrites file
aAppend – Adds to the end of file
xCreate – Fails if file already exists

1. Write to a File (w mode)

with open("demo.txt", "w") as f:
   f.write("Hello, Python!\n")
   f.write("This is file writing example.")

Output in demo.txt:

Hello, Python!
This is file writing example.

Explanation:

  • w mode overwrites if file exists, otherwise creates a new one.
  • f.write() writes a string to the file.
  • Use \n for a new line.

2. Append to File (a mode)

with open("demo.txt", "a") as f:
   f.write("\nAppended line here.")

Output in demo.txt after append:

Hello, Python!
This is file writing example.
Appended line here.

Explanation:

  • a mode adds data to the end of the file without erasing previous content.

3. Create a New File (x mode)

with open("newfile.txt", "x") as f:
   f.write("This file is created using 'x' mode.")

Output in newfile.txt:

This file is created using 'x' mode.

Explanation:

  • x creates a new file and raises an error if the file already exists.

Handle File Already Exists Error (with x mode)

try:
   with open("newfile.txt", "x") as f:
       f.write("Trying to create existing file.")
except FileExistsError:
   print("File already exists.")

Output:

File already exists.

Extra Tip: Write Multiple Lines

lines = ["First line\n", "Second line\n", "Third line\n"]
with open("multi.txt", "w") as f:
   f.writelines(lines)

Output in multi.txt:

First line
Second line
Third line

Explanation:

  • writelines() writes a list of strings into the file.
  • Make sure each line includes \n manually.

Real-World Example: Log to a File

import datetime
with open("log.txt", "a") as log:
   log.write(f"Log entry at {datetime.datetime.now()}\n")

Sample log.txt:

Log entry at 2025-06-16 10:30:12.982139

Explanation:
Appends a timestamp every time the code runs—useful for error logging or activity tracking.

Summary

TaskModeBehavior
Overwrite filewDeletes previous content
Append to fileaKeeps existing content
Create new filexFails if file exists