FileIO & Exceptions
Read & Write Files in Python
file = open(./file_path/file.ext, ‘mode’)
make sure to close your open files.
reader = open('dog_breeds.txt', 'r')
try:
# Further file processing goes here
finally:
reader.close()
or
with open('dog_breeds.txt', 'r') as reader:
# Further file processing goes here
- modes
- r - read
- w - write
- a - append
- rb / wb - in binary mode
- .read(size=-1)
- This reads from the file based on the number of size bytes. If no argument is passed or None or -1 is passed, then the entire file is read.
- .readline(size=-1)
- This reads at most size number of characters from the line. This continues to the end of the line and then wraps back around. If no argument is passed or None or -1 is passed, then the entire line (or rest of the line) is read.
- .readlines()
- This reads the remaining lines from the file object and returns them as a list.
- .write(string)
- This writes the string to the file.
- .writelines(seq)
- This writes the sequence to the file. No line endings are appended to each sequence item. It’s up to you to add the appropriate line ending(s).
Exceptions in Python
- raise allows you to throw an exception at any time.
- assert enables you to verify if a certain condition is met and throw an exception if it isn’t.
- In the try clause, all statements are executed until an exception is encountered.
- except is used to catch and handle the exception(s) that are encountered in the try clause.
- else lets you code sections that should run only when no exceptions are encountered in the try clause.
- finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.
References