Course 2.1Lesson 1 of 5
A file keeps text after the program ends. open with a name and a mode gives a file object, and the with statement closes it for you. The mode r reads and needs the file to exist, w writes and empties a file that exists, and a adds to the end and keeps the old text. read gives the whole text, readlines a list of lines, and a loop over the file gives one line at a time, each ending with a newline that strip removes. write does not add a newline, so you add it. A missing file raises a FileNotFoundError, which try and except can handle, and os.path.exists asks first.
Try the code and the simulations beside the lesson.
After this lesson you can
"r", "w" and "a",with so that the file is always closed, andEverything that your program knows, in its variables, disappears when it ends. A list of marks that took an hour to type is gone. A file keeps data on the disk, so that it is there the next time, and so that another program can read it. Files are how programs remember.
On this site, your code runs inside your browser, with a small private disk of its own. Files that you make there work like real files, for the time that the page is open. On your own computer, they are real files in a folder.
Predict first. How many characters will the text have? Then run it.
At the end there are two more ways to write. f.writelines(...) writes a list of texts, but it does not add the new lines for you. And print("delta", file=f) uses the familiar print, which does add the new line. Both work. Choose the one that reads best.
Choose the mode for the job: "w" for a fresh report, "a" for a log that grows, and "r" (the default) only to read.
Which is better? With a file, try and except is often the better style: between the moment you ask "does it exist?" and the moment you open it, something may change. Opening and handling the error is a single step.
\n with write. All the lines join into one long line."w" a file that you wanted to add to. The old text is gone. Use "a".io.UnsupportedOperation error.\n. Compare line.strip() and not line.with. The file may stay open.FileNotFoundError.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
with open(name, mode) as f: opens a file and always closes it."r" reads, "w" writes and empties, "a" adds to the end.write does not add a newline. A loop over a file gives lines that end with \n.FileNotFoundError. Handle it with try and except.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
open("a.txt", "w") do if a.txt already holds text?\n, and does write add it for you?with better than open and close?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.