Writing Files

To write a file, you have to open it with mode ‘w’ as a second parameter:
>>> fout = open('out.txt', 'w')
>>> print fout

If the file already exists, opening it in write mode clears out the old data and starts fresh if the file doesn’t exist, a new one is created.
The write method of the file handle object puts data into the file.
>>>line1 = ‘Lord of the Rings is awesome movie.’
>>>fout.write(line1)
Again, the file object keeps track of where it is, so if you call write again, it adds the new data to the end. We must make sure to manage the ends of lines as we write to the file by explicitly inserting the newline character when we want to end a line. The print statement automatically appends a newline, but the write method does not add the newline automatically.
>>> line2 = '\n Terminator 4 is not so great\n'
>>> fout.write(line2)
When you are done writing, you have to close the file to make sure that the last bit of data is physically written to the disk so it will not be lost if the power goes off.

Nema komentara:

Objavi komentar