0% found this document useful (0 votes)
6 views

DFOR510 Week10 Python Files Hash Err

The document discusses Python libraries for handling files, errors, and hashing. It covers the os, base64, hashlib and Crypto libraries. It describes opening, reading, writing and appending to files as well as handling exceptions using try/except blocks.

Uploaded by

DA MV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DFOR510 Week10 Python Files Hash Err

The document discusses Python libraries for handling files, errors, and hashing. It covers the os, base64, hashlib and Crypto libraries. It describes opening, reading, writing and appending to files as well as handling exceptions using try/except blocks.

Uploaded by

DA MV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

George Mason University

Python – Handling Files & Errors, Hashing


▪ Python libraries: os & Base64

▪ Hashing with Python

▪ Handling files

▪ Error Handling, Try/Except

2
3
1. Libraries
❑ Identify standard vs. third party
❑ Import shortcuts and best practices
❑ Using the ‘os’ library for portability

2. Hashing…
❑ With Python libraries: hashlib & Crypto.Hash

3. File Handling
❑ Learn how to open, read, write, and append to files
❑ Identifying where file pointers are for various file modes

4. Error Handling
❑ Identify ‘Errors’ vs ‘Exceptions’
❑ Gracefully handle exceptions in Python scripts 4
5

standard vs third party libraries, and more…


▪ Allow us to import functions from other scripts so that we
don’t have to recreate pre-existing code/functions

▪ Two types of library:


▪ Standard – come with every Python installation; commonly used
code supported by the software foundation

▪ Third-party – introduce new code, add or improve functionality to a


standard Python installation
Which library type would your programs be considered?

6
▪ Use ‘import’ to include a particular library in your module

Which one does PEP


tell us to use?

7
▪ Allows user to port python script easily between various
operating systems using os dependent functions

▪ os library functions:
▪ os.name – name of the operating system dependent module
imported
▪ os.path – yields path where Python is executed from
▪ os.chdir(“C:\”) – go to C:\ directory
▪ os.getcwd( ) – what directory are you currently working in
▪ os.walk(directory) – traverse directory’s folder from top-down
(default), or bottom-up
10
▪ Used to encode/decode ASCII text to binary formats.

▪ base64 library functions:


▪ base64.decode(b64Object) - decode the Base64 encoded bytes
object or ASCII string and return the decoded bytes to human
readable text

▪ base64.encode(byteObject) - encode bytes object using base64


and return the encoded bytes
Decode the following (hint, they are not both Base64)
JBSWY3DPEBBUMUSTGUYTAIJAKRUGS4ZANFZSAYJAIJQXGZJW SGVsbG8gQ0ZSUzUxMCEgVGhpcyBpcyBhIEJhc2U2NCBlbmNvZGl
GQQGK3TDN5SGS3THF5SGKY3PMRUW4ZZAMV4GC3LQNRSS4C uZy9kZWNvZGluZyBleGFtcGxlLgpZb3Ugd2lsbCBuZWVkIHRvIGxlYX
SZN52SA53JNRWCA3TFMVSCA5DPEBWGKYLSNYQGQ33XEB2G6I JuIGhvdyB0byBkZWNvZGUgYmFzZTY0IHRleHQgZm9yIEhXMy4=
DEMVRW6ZDFEBRGC43FGY2CA5DFPB2CAZTPOIQEQVZTFY==== 12
==
OS & BASE64 LIBRARIES
From BB → Course Content → Class10… → Exercises

Download:
❑ osBase64 (.ipynb or .py)

Run through the cell in note any questions/issues/comments you


have for each step.

Complete the QUICK CHECK with your group. 13


QUICK CHECK 1
1. Any Python script that you write would be considered a ___
library.
a. Standard b. Third Party

2. PEP 8 recommends which method for importing multiple


libraries?
a. b.

3. This command allows us to change our current working


directory.
14
15
16
17
HASHING WITH PYTHON
From BB → Course Content → Class10… → Exercises

Download:
❑ hashWpython (.ipynb or .py)

Run through the cell in note any questions/issues/comments you


have for each step.

Complete the QUICK CHECK with your group. 18


QUICK CHECK 2
1. The digest() method returns what type of response?
hexdigest()?
2. Before calling the hash method (e.g. md5, sha256, etc,)
what must be done first to the content you wish to hash?

3. T or F. When using the Crypto.Hash library, we must


create an object with the new() method.

19
20

http://www.99points.info/wp-content/uploads/2010/03/filetypes.png
File Mode Description
r Read – opens the file for read-only mode (default)
w Write – creates the file for writing; overwrites file it if already
exists
a Append – writes data at the end of a file; creates file if it
doesn’t already exist
rb, wb, or ab Binary mode – read or write file in binary mode
r+, rb+, w+, wb+, a+, or ab+ Read/Write – read and write files in standard or binary mode

21
▪ File object are created with open() method
▪ Syntax:
▪ open(filename, fileMode)
▪ inFile = open(‘week09_test.txt’)
▪ inFile = open(‘week09_test.txt’, ‘w’)
▪ inFile = open(‘week09_test.txt’, ‘rb’)
▪ inFile = open(‘week09_test.txt’, ‘a’)

22
http://www.potrebitel-russia.ru/uploads/images/t_7_t.jpg
Reading file objects Writing file objects
▪ read(), readline(), ▪ write(), writelines()
readlines() ▪ inFile.write(content)
▪ inFile.read() ▪ inFile.writelines(list_of_li
▪ Can specify number of nes)
bytes to be read
▪ inFile.readline()
▪ inFile.readlines()

23
https://thumbs.dreamstime.com/b/cartoon-open-book-bookmark-icon-isolated-white-background-eps-file-available-86598551.jpg
http://www.clker.com/cliparts/m/e/w/W/Z/3/pencil-and-paper-hi.png
▪ Python automatically closes files objects when done with
them
▪ However, good coding practice dictates we flush and close
file objects after writing to them:
▪ inFile.flush()
▪ inFile.close()

24
https://cdn-images-1.medium.com/max/670/1*wPqqYFfNreXF4INrNhYkeQ.jpeg
▪ When analyzing images or files, we may want to read files
in raw, or binary, format
▪ week09_1 = open(r‘C:\...\week09_image1.jpg’, ‘rb’)
▪ week09_1.tell()
▪ week09_1.read(# of bytes)
▪ week09_1.seek(offset, from_position)
▪ Where from_position is:
▪ 0 : from start of file - default
▪ 1: from current position
▪ 2: from end of file
25
http://inventionmachine.com/Portals/56687/images/engineers_seek.jpg
HANDLING FILES
From BB → Course Content → Class11… → Exercises

Download:
❑ handlingFiles (.ipynb or .py)
❑ lect11_1.jpg
❑ Lect11_test.txt (make a copy of this file after downloading)

Run through the cell in note any questions/issues/comments you


have for each step.
Complete the QUICK CHECK with your group. 26
QUICK CHECK 3
1. Where in the file is the file pointer: Start or End
Operation Mode Pointer Location
open(file, “rb”)
open(file, “a+”)
Open(file, “wb+”)

2. What will the tell() method print to the console on Line 5?

27
28

Try/Except
▪ Errors – ▪ Exceptions –

29
ImportError/ import module doesn’t exist or couldn’t be
ModuleNotFound found
FileNotFoundError
ValueError trying to perform an illegal operation on an
object (e.g. int(“error”))
IndexError attempting to index an item in a location that
doesn’t exist
AttributeError trying to perform an illegal method on an object
TypeError e.g. list(1024) – trying to cast an integer as a list
NameError value doesn’t exist
31
▪ Unhandled
exception

▪ Handled
exception

32
▪ Why did this
code crash?

▪ What caused
the ‘except’
condition?
33
▪ Handling
multiple
exceptions

34
ERROR HANDLING
From BB → Course Content → Class10… → Exercise

Download:
❑ ErrorHandling (.ipynb or .py)

Run through the cell in note any questions/issues/comments you


have for each step.

Complete the QUICK CHECK with your group. 35


QUICK CHECK 4
1. _____ occur at runtime, while _____ are due to syntax
errors.

2. If you attempt to use a variable that has not been defined,


what error will you encounter?

36
38
https://clipartfox.com/categories/view/8afc348758b19996c75d34ea32d903b144a67dca/spring-break-2017.html
Hashing
https://docs.python.org/3.7
https://pycryptodome.readthedocs.io/en/latest/src/hash/hash.html
https://pycryptodome.readthedocs.io/en/latest/src/hash/hash.html

Base64
https://blogs.oracle.com/rammenon/base64-explained
http://www.rfc-editor.org/rfc/rfc4648.txt

39
40
41

You might also like