>>> f = open('workfile', 'rb+') >>> f.write(b'0123456789abcdef') 16 >>> f.seek(5) # Go to the 6th byte in the file 5 >>> f.read(1) b'5' >>> f.seek(-3, 2) # Go to the 3rd byte before the end 13 >>> f.read(1) b'd'
Here is what the above code is Doing:
1. The first argument to open gives the file name. The second argument specifies the mode in which the file is opened. Here, the mode is ‘rb+’, which means open for reading and writing in binary mode.
2. The write method writes a string of bytes.
3. The seek method changes the file position. 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 means absolute file positioning, 1 means seek relative to the current position, and 2 means seek relative to the file’s end.
4. The read method reads up to size bytes from the file (less if the read hits EOF before obtaining size bytes).
5. The tell method returns the file’s current position, like seek(0,1).
The mode argument is optional; ‘r’ is the default when mode is omitted. Other common values are ‘w’ for write-only files, ‘a’ for append-only files, and ‘r+’ for reading and writing files. These modes do not require the ‘b’ in the mode argument.
The seek method is used to change the file position. The new position is computed by adding offset to a reference point; the reference point is selected by the whence argument. A whence value of 0 means absolute file positioning, 1 means seek relative to the current position, and 2 means seek relative to the file’s end.
The tell method returns the file’s current position, like seek(0,1).
The readinto method reads data from the file and stores it into a buffer. The buffer should be at least the size of the read data.
The write method writes the string s to the file, returning the number of bytes written.
The writelines method writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value.
The truncate method resizes the file to the specified size.
The flush method is a hint to the implementation that it can flush internal buffers to disk. This is not normally needed, but if you are working with very large files, you may want to call this from time to time to minimize the risk of losing data in memory if the system crashes.
The close method closes the file. Any buffered data is flushed first.