From 78a209afa4cae7c80340fab74dd219316246cf7b Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Sat, 18 Jul 2009 22:29:05 -0400 Subject: [PATCH] started #writing section --- files.html | 87 +++++++++++++++++++++++++++--------------------------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/files.html b/files.html index fe4c577..bcad2fa 100644 --- a/files.html +++ b/files.html @@ -259,37 +259,36 @@ ValueError: I/O operation on closed file.

Writing to Text Files

-

FIXME +

You can write to files in much the same way that you read from them. First you open a file and get a file object, then you use methods on the file object to write data to the file, then you close the file. + +

To open a file for writing, use the open() method and specify the write mode. There are two file modes for writing: - +

  • You start boldly by creating the new file test.log (or overwriting the existing file), and opening the file for writing. The mode='w' parameter means open the file for writing. Yes, that’s all as dangerous as it sounds. I hope you didn’t care about the previous contents of that file (if any), because that data is gone now. +
  • You can add data to the newly opened file with the write method of the file object returned by the open() function. After the with block ends, Python automatically closes the file. +
  • That was so fun, let’s do it again. But this time, with mode='a' to append to the file instead of overwriting it. Appending will never harm the existing contents of the file. +
  • Both the original line you wrote and the second line you appended are now in the file test.log. Also note that carriage returns are not included. Since you didn’t write them explicitly to the file either time, the file doesn’t include them. You can write a carriage return with the '\n' character. Since you didn’t do this, everything you wrote to the file ended up on one line. +

    Character Encoding Again

    @@ -368,21 +367,21 @@ calls the object’s read method, the function can handle any k