Moves the file pointer in a file previously opened with create( ) or open( ), and returns the new position of the file pointer.

Syntax

<oRef>.seek(<offset expN> [, <position expN>])

<oRef>

A reference to the File object that created or opened the file.

<offset expN>

The number of bytes to move the file pointer in the specified file. If <offset expN> is negative, the file pointer moves toward the beginning of the file. If <offset expN> is 0, the file pointer moves to the position you specify with <position expN>. If <offset expN> is positive, the file pointer moves toward the end of the file or beyond the end of the file.

<position expN>

The number 0, 1, or 2, indicating a position relative to the beginning of the file (0), to the file pointer’s current position (1), or to the end of the file (2). The default is 0.

Property of

File

Description

seek( ) moves the file pointer in the file you specify relative to the position specified by <position_expN>, and returns the resulting position of the file pointer as an offset from the beginning of the file. The File object’s position property is also updated with this new position. If an error occurs, seek( ) returns –1.

The movement of the file pointer is relative to the beginning of the file unless you specify otherwise with <position expN>. For example, seek(5) moves the file pointer five characters from the beginning of the file (the 6th character) while seek(5,1) moves it five characters forward from its current position. You can move the file pointer beyond the end of the file, but you can’t move it before the beginning of the file.

To move the file pointer to the beginning of a file, use seek(0). To move it to the end of a file, use seek(0, 2). To move to the last character in a file, use seek(–1,2).

gets( ), puts( ), read( ), and write( ) also move the file pointer as they read from or write to the file.