File Input/Output
Lesson 1 of 1
  1. 1
    Until now, the Python code you’ve been writing comes from one source and only goes to one place: you type it in at the keyboard and its results are displayed in the console. But what if you want to…
  2. 2
    Let’s walk through the process of writing to a file one step at a time. The first code that you saw executed in the previous exercise was this: f = open(“output.txt”, “w”) This told Python to o…
  3. 3
    Good work! Now it’s time to write some data to a new .txt file. We added the list comprehension from the first exercise to the code in the editor. Our goal in this exercise will be to write each e…
  4. 4
    Excellent! You’re a pro. Finally, we want to know how to read from our output.txt file. As you might expect, we do this with the read() function, like so: print my_file.read()
  5. 5
    What if we want to read from a file line by line, rather than pulling the entire file in at once. Thankfully, Python includes a .readline() method that does exactly that. If you open a file and ca…
  6. 6
    We keep telling you that you always need to close your files after you’re done writing to them. Here’s why! During the I/O process, data is buffered: this means that it is held in a temporary lo…
  7. 7
    Programming is all about getting the computer to do the work. Is there a way to get Python to automatically close our files for us? Of course there is. This is Python. You may not know this, but …
  8. 8
    It worked! Our Python program successfully wrote to text.txt.
  9. 9
    Finally, we’ll want a way to test whether a file we’ve opened is closed. Sometimes we’ll have a lot of file objects open, and if we’re not careful, they won’t all be closed. How can we test this? …

What you'll create

Portfolio projects that showcase your new skills

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory