Week 2 subject 1: File Operations
- File means text files. It's a giant leap forward which means you are finally free from keystrokes and can now process something much more complex and more meaningful!
- Always use the open() function to open a file before using, which returns a File object you'll need to refer to whenever you need to operate a file.
- Always use the .close() method to close the file after use.
- Read from files using:
- .read(number of characters)
- .readline()
- 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
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(offset, from) moves forward or backward in file,
- .tell() tells the current position in file.
No comments:
Post a Comment