...

/

Writing to Text Files

Writing to Text Files

We'll cover the following...

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

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

  • Write” mode will overwrite the file. Pass mode='w' to the open() function.
  • “Append” mode will add data to the end of the file. Pass mode='a' to the open() function.

Either mode will create the file automatically if it doesn’t already exist, so there’s never a need for any sort of fiddly “if the file ...