CodeBlanks Logo Icon CodeBlanks

write and writelines

Learn writing with write and writelines.

write and writelines

To write text into a file, use the write method: f.write("Hello\n"). This method writes the string as is; you add the \n for a line break yourself. The return value is the number of characters written.

To write many lines at once, use writelines: f.writelines(["a\n", "b\n", "c\n"]). It writes the list of strings in order; it doesn't add \n between them, so you add it yourself.

The write return value

The write method returns the number of characters written. If you write n = f.write("Hello world"), then n is 11. This is handy for tracking progress with large data.

Turkish characters can take more than one byte in UTF-8; still, write returns the character count. To see the byte count, you'd need to open the file in binary mode.

Practice Write three lines with writelines

Open a file for writing: f = open("list.txt", "w", encoding="utf-8"). Write three lines with f.writelines(["apple\n", "pear\n", "cherry\n"]) and close it. Reopen it in read mode, get the lines with lines = f.readlines(), print the count with print(len(lines)) and close it.

Starter code

main.py
# Write three lines with writelines and close
# Reopen, read with readlines, print the count

Sample solution

main.py
# Write three lines with writelines and close
f = open("list.txt", "w", encoding="utf-8")
f.writelines(["apple\n", "pear\n", "cherry\n"])
f.close()
# Reopen, read with readlines, print the count
f = open("list.txt", "r", encoding="utf-8")
lines = f.readlines()
print(len(lines))
f.close()

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the writing methods

Term Meaning
write Writes one string
writelines Writes a list of strings
read Reads all content
close Closes the file

2 Does writelines add \n between items?

  • Yes, it adds one automatically between each
  • No, it only writes the strings in order Correct answer
  • Only to the last string
  • Only to the first string

Explanation: writelines only writes the strings in order; you add the \n yourself.

3 Complete the write method

Question
f.____("Hello
")
Answer
f.write("Hello
")

Explanation: write writes a single string.

All lessons in Intermediate