Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 04

Writing Files — write() and writelines()

Write text into a Python file with write() and writelines(), and convert numbers to strings before they are stored as characters.

Intermediate25 min
Writing files hero Module 16 Lesson 4 write and writelines

Writing transfers object data from memory into a file. Both write methods accept strings, not raw numbers.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • The three steps of a write operation
  • write() for one string
  • writelines() for an iterable of strings
  • Why numbers must be converted with str() first
  • Which errors can appear while creating or opening the file

The idea

Steps for a write operation

A write operation saves a memory object as a record. The steps are:

  1. Choose the file name.
  2. Open that name in a write mode such as "w" or "a".
  3. Call a write method once for each piece you want to store.

handle.write(text) writes one string. If the value is an int or a float, convert it with str() first. write() does not accept a number.

handle.writelines(lines) writes every string in an iterable. Pass a list of strings, and put \n on each line if you want line breaks. Do not wrap the whole list in str(). str(some_list) is one string of characters, and writelines would then write those characters one by one in a way you did not mean. Convert each field yourself, then pass the list of strings.

write() and writelines() still store values one call at a time. When the object should be saved in a single write, the later pickling lesson is the tool for that.

While opening for write you may see OSError for a bad path, or FileExistsError if you used exclusive mode x and the name was already taken. IOError is the older name; in current Python that failure shows up as OSError.

Example

python
seat = 12
label = "Avery Lane"
with open("notebook.txt", "w", encoding="utf-8") as handle:
    handle.write(str(seat) + "\t")
    handle.write(label + "\n")
    lines = ["Jordan Hale\n", "Mina Cole\n"]
    handle.writelines(lines)

The playground writes the same file and then reads it back so you can see the tab and the two extra lines. Edit the names and run again. "w" replaces the file on every run.

Key takeaways

  • Choose a name, open in a write mode, then write

  • write() takes one string

  • writelines() takes an iterable of strings

  • Convert numbers with str() before writing

  • One call stores one chunk; pickling later stores a whole object at once

  • Previous: open() and with open()

  • Next: read() and readlines()

Loading playground…

Check your understanding

Writing files quiz

write() accepts:

1 / 10