Lesson 96 +10 XP

Write and Create Files

Write and Create Files

To add content to a file, open it in "a" or "w" mode and use write().

Append with "a"

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

Appending adds at the end and keeps existing content.

Write with "w"

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

The "w" mode overwrites existing content or creates the file if it doesn't exist.

Create a new file

Use "w" for a new file, or "x" to be safe against overwriting.

f = open("brandnew.txt", "w")
f.write("Hello!")
f.close()

Verify the content

After writing, open in "r" and print:

f = open("demofile2.txt", "r")
print(f.read())

write() takes a string

Only strings can be written. Convert numbers first:

f.write(str(42) + "\n")

TL;DR

  • "a" appends; "w" overwrites or creates.
  • write(text) adds content.
  • Close the file to flush changes.
  • Only strings can be written.