Reading 3
Reading and Writing Python Files
What exactly is a file?
…a file is a continguous set of bytes used to store data.
### Parts of a Modern File
- Header - the overall information about the file (name, size, type, etc)
- Data - the meat and potatoes of the file
- End of File (EOF) - a characted marking the end of the file.
Opening and Closing Files in Python
- Open - open(‘filename.ext’)
- Once open always make sure to close the file when done.
- Try and Finally help here:
- Closing
reader = open('my_file.txt) try: # Do some things finally: reader.close()
Ok Now What?
-.read() - reads entire file -.realine() - reads entire line -.readlines() - reads remaining lines from file -.write(string) - does what it says -.writelines(seq) - writes with no line endings, that is up to you
Exceptions
- raise can be used to throw an exception if a particular condition occurs.
x = 3 if x > 30: raise Exception('X shoul d exceed 30')
- try/except blocks are used to like try/catch in JS
- ‘error’ may also be used as keyword and printed (except AssertionError as error: print(error) )
- A try block will be exectued until the point an exception occurs, then skips any remaining code into the except block
- an ‘else’ block may be used at the end, and is run if there are no exceptions
- ‘finally’ blacks will run no matter the exception status