File Access

Opening files

fileobject = open(filename, mode)
mode: [r, w, a, r+][b]   (default: r)
r read-only (default)
w write-only (existing file erased)
a append (add to the end of existing file)
r+ read-write
b binary mode (for portability to Windows, Macintosh)

Reading files

string = fileobject.read([size])
  • By default, the entire file is read (the same applies if size is negative).
string = fileobject.readline()
  • Reads the current line, including the \n character.
  • Returns an empty string if the end of the file has been reached.
list = fileobject.readlines()
  • Reads the entire file, returning a list of each line.

Writing files

fileobject.write(string)

fileobject.writelines(list)
  • Writes a list of strings to the file.

File position

integer = fileobject.tell()
  • Gets the current file position (0-based).
fileobject.seek(offset, relative_to)
relative_to: [0, 1, 2]   (default: 0)
0 Beginning of the file
1 Current file position
2 End of the file
  • Changes the file position.

Closing files

fileobject.close()