Instruction
All right, it's time to wrap things up!
-
To open and close a file, use:
file = open('filename') ... file.close() file.read()reads the contents of the given file.file.write('text')writes 'text' to the given file.open('filename', 'mode')can use, among others, the following modes:'r'– read only;'w'– write only – by creating or replacing an existing file;'a'– append – add contents to the end of the file;
- To read a file line by line, use:
file = open('filename') for line in file: ... file.close() - The
withstatement can be used to automatically close a file:with open('filename') as file: ... - To handle exceptions, use:
try: ... except ErrorType: ...
- ErrorTypes include
IOErrorandValueError, but there are many more.
Are you ready for a short quiz now?
Exercise
Click to continue.



