Register to get access to free programming courses with interactive exercises

Line-by-line reading and writing Python: Text Input/Output Fundamentals

In the previous lesson, we mentioned that consecutive calls to the write method append text to the end. Here we are going to continue with this topic and learn how to work with files line by line.

How to write text line-by-line

We often have an iterator that provides text line by line. Of course, you can write a loop, but there's a better way — the writelines method. Here's how it works:

f = open("foo.txt", "w")
f.writelines(["cat\n", "dog\n"])
f.close()
f = open("foo.txt", "r")
print(f.read())
# => cat
# => dog

f.close()

As you can see, we wrote all the lines in the correct order. This approach is preferable when you need to write a large amount of text that you receive and process line by line. It's possible to accumulate the entire text in a single string beforehand, but it may require much memory. We should write the lines as they become available, and writelines is perfect.

How to read text line-by-line

You can not only write to a file line by line but also read it in the same way:

f = open("foo.txt")
f.readline() # 'cat\n'

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
new
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.