Chapter 7. Input and Output 54 Python Tutorial, Release 3.9.5 7.2.1 Methods of File Objects The rest of the examples in this section will assume that a file object called$_{f}$ has already been created. To read a file’s contents, call f.read(size) , which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached,$_{f.read()}$ will return an empty string ($_{''}$ ). f.readline() reads a single line from the file; a newline character ($_{
}$) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '
' , a string containing only a single newline. For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: If you want to read all the lines of a file in a list you can also use$_{list(f)}$ or$_{f.readlines()}$ . f.write(string) writes the contents of string to the file, returning the number of characters written. Other types of objects need to be converted – either to a string (in text mode) or a bytes object (in binary mode) – before writing them: f.tell() returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode. To change the file object’s position, use$_{f.seek(offset, whence)}$ . The position is computed from adding offset to a reference point; the reference point is selected by the whence argument. A whence value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. whence can be omitted and defaults to 0, using the beginning of the file as the reference point. (continues on next page) >>> f =open('workfile','rb+') >>> f.write(b'0123456789abcdef ') 16 >>> f.seek(5) # Go to the 6th byte in the file >>> value=('the answer',42 ) >>> s =str(value) # convert the tuple to string >>> f.write(s) 18 >>> f.write('This is a test ') 15 >>>for line in f: ... print(line, end ='') ... This is the first line of the file. Second line of the file >>> f.readline() 'This is the first line of the file.
' >>> f.readline() 'Second line of the file
' >>> f.readline() '' >>> f.read() 'This is the entire file.
' >>> f.read() ''