Saturday, March 7, 2026

Week 5 Learning Summary

Week 5 subject 1: File Operations (cont.)

  • Pay attention lines read from a File contain the newline characters at the end of each line.
  • You can use File like a list of lines with for l in f: 
  • ATTENTION: the File object keeps track of the current position read.  It always moves forward.

  • More ways to process File contents in Lists:
  • List(File) is a list of lines from File,
  • .readlines(hint) returns a list of lines.
  • One way to avoid explicitly closing files is using 
        with open(Filename) as File:

            File will be automatically closed at the end of the with block.

  • Opening files for output using the 'w' or 'a' modes in the open() function.  Note the different behaviour vs. 'r' when the file doesn't exist.
  • Output to files with the write() function.
  • Files by default is a sequential media.  There's a historical reason for this.  However there are ways to move in a file in both directions:
  • .seek(offsetfrom) moves forward or backward in file,
  • .tell() tells the current position in file.

No comments:

Post a Comment