Menu

File Handling

Writing to a text file

Once a file has been opened in write mode, the write() method puts text into it. You call it on the file object and pass one string, and that text is added at the point the file has reached. Two calls in a row join their text together, so you must decide where each line ends.

Only strings can be written

write() accepts a string and nothing else. A value such as 12.5 has to be turned into text first with str(), so str(12.5) gives the string "12.5". Python will not do this for you: passing a number straight in stops the program with an error, because write() only deals in text.

You add the newline yourself

write() stays on the same line when it finishes, so strings written with nothing extra end up squashed together into one very long line. To store one value per line, end each string with the newline character "\n". It is a single invisible character that marks where the line ends, so the next value starts on the line below.

For example, a weather station saves three morning temperatures. For each reading the program converts the number with str(), adds "\n" on the end, and writes the result, so the file ends up holding three lines with one reading on each. You can also build a whole line with + before writing it: joining a label, the converted reading and a unit gives a line such as Morning 1: 12.5 degrees.

Practise this