🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Python Notes
Topic #114

Python Write/Create Files


Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example

with open("demofile.txt", "a") as f:
  f.write("Now the file has more content!")

#open and read the file after the appending:
with open("demofile.txt")
as f:
  print(f.read())

Overwrite Existing Content

To overwrite the existing content to the file, use the w parameter:

Example

with open("demofile.txt", "w") as f:

f.write("Woops! I have deleted the content!")

#open and read the file after the overwriting:
with open("demofile.txt")
as f:

print(f.read())

Note: the "w" method will overwrite the entire file.


Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exists

"a" - Append - will create a file if the specified file does not exists

"w" - Write - will create a file if the specified file does not exists

Example

f = open("myfile.txt", "x")

Result: a new empty file is created.

Note: If the file already exists, an error will be raised.

Want to go beyond the notes?

Join CodingNow 2.0's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Python Write/Create Files – FAQs

Quick answers about learning Python Write/Create Files in Python.

This free note from CodingNow 2.0 explains Python Write/Create Files in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on CodingNow 2.0, including Python Write/Create Files, is 100% free with no signup required.
With focused practice, most students grasp Python Write/Create Files in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now