September 2013
Intermediate to advanced
350 pages
9h 38m
English
This program opens a file called topics.txt, writes the words Computer Science to the file, and then closes the file:
| | with open('topics.txt', 'w') as output_file: |
| | output_file.write('Computer Science') |
In addition to writing characters to a file, method write returns the number of characters written. For example, output_file.write(’Computer Science’) returns 16.
To create a new file or to replace the contents of an existing file, we use write mode (’w’). If the filename doesn’t exist already, then a new file is created; otherwise the file contents are erased and replaced. Once opened for writing, you can use method write to write a string to the file.
Rather than replacing the file contents, we can also add to ...
Read now
Unlock full access