首页 > 代码库 > Reading and writing

Reading and writing

A text file is a sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM. To read a file, you can use open to create a file object:

                       

Mode ‘r’ means that file is open for reading. The file object provides several methods for reading data, including readline.

The file object keeps track of where it is in the file, so if you invoke readline again, it picks up from where it left off. You can also use a file object in a for loop.

To write a file, you have to create a file object with mode ‘w’ as a second parameter. 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 puts data into the file. Again, the file object keeps track of where it is, so if you call write again, it add the new data to the end. When you done writing, you have to close the file.

 

 

 

The write function returns the length of the string, including the ‘\n’ at the end of the string.

 

from Thinking in Python

Reading and writing