Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading...

21
Python Programming Dr Diarmuid Ó Briain

Transcript of Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading...

Page 1: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Python Programming

Dr Diarmuid Ó Briain

Page 2: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Files and databases

Page 3: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Testing if files or directories exist

$ mkdir my_directory$ echo "FILE" > my_directory/file.txt

$ python3>>> from os import path>>> my_dir = 'my_directory'>>> my_file = 'my_directory/file.txt'>>> other_file = 'my_directory/file2.txt'

>>> path.exists(my_dir)True>>> path.exists(my_file)True

>>> path.isdir(my_dir)True>>> path.isdir(my_file)False

my_directory file.txt

>>> path.isfile(my_file)True>>> path.isfile(other_file)False

Page 4: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Writing to files

$ ./write2file.py

$ cat file.txt This is a test filethat I want to write toSome more textfinished.

Modesr Readw Writea Append

Page 5: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Reading files

$ ./readafile.py

** Reading entire file, this is the output **

(<class '_io.TextIOWrapper'>, <_io.TextIOWrapper name='file.txt' mode='r' encoding='UTF-8'>)This is a test filethat I want to write toSome more textfinished.

** Changing something **

This is a test filethat I want 2 write 2Some more textfinished.

** Reading the file, line by line **

This is a test filethat I want to write toSome more textfinished.

Page 6: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Interfacing with databases

$ ./working_with_db.py Enter a label: aaEnter a label: bbEnter a label: ccEnter a label: ddEnter a label: eeEnter a label: ffEnter a label: ggEnter a label: hhEnter a label: iiEnter a label: jj

Committing labels to the database.

$ sqlite3 my_first_db.sqliteSQLite version 3.8.2 2013-12-06 14:53:30Enter ".help" for instructionsEnter SQL statements terminated with a ";"

sqlite> select * from Test_table;1|aa2|bb3|cc4|dd5|ee6|ff7|gg8|hh9|ii10|jjsqlite>

Page 7: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Interfacing with databases

● SQLite Database Browser

Page 8: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Exercise 11

Page 9: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Handling Errors

Page 10: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Errors

● Stopping a program and passing a reason to the Operating System maybe necessary to deal with exceptional situations in code.

$ ./my_error.py 0 is less than 31 is less than 32 is less than 33 must not be less than 3 after allError it failed

$ echo $?1

Page 11: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

sys.exit()

● sys.exit() is a little more interesting. ● It does not immediately call the libc function exit(), but

instead raises a SystemExit[1] exception. ● So the same can be achieved using the following

syntax. $ ./my_error.py 0 is less than 31 is less than 32 is less than 33 must not be less than 3 after all$ echo $?1

Page 12: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

os._exit()

● os._exit() is a thin wrapper around the libc function exit()

● It does not raise an exception and leaves the program immediately.

$ ./my_error.py 0 is less than 31 is less than 32 is less than 33 must not be less than 3 after all

$ echo $?1

Page 13: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

try/except

● os._exit() is a thin wrapper around the libc function exit()

● It does not raise an exception and leaves the program immediately.

$ echo "no" > no_read_file.no

$ ./my_try_except.py no

$ echo $?0

$ chmod 333 no_read_file.no

$ ./my_try_except.py Cannot open no_read_file.no file

$ echo $?1

Page 14: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Python Exception Classes

● Hierarchy of exceptions– non-fatal errors - allow execution to continue– fatal errors - halt execution of the program

+-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError

Page 15: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Example

● Two files and a directory● One file owned by root● Directory and other file owned by user alovelace

$ sudo cat root_file.txt Root file

$ cat user_file.txt User file

$ ls -la | grep '_file'-rw------- 1 root root 10 Feb 24 14:25 root_file.txtdrwxrwxr-x 2 alovelace alovelace 4096 Feb 24 15:10 user_file_dir-rw-rw-r-- 1 alovelace alovelace 299 Feb 24 15:12 user_file.txt

Page 16: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Example

● Program to write to files● Exceptions built in to handle errors

– Permission error– Is a directory error

cat write_to_files.py#! /usr/bin/env python3

file_list = ['user_file_dir', 'root_file.txt', 'user_file.txt']

for x in file_list: try: fh = open(x, "a") fh.write(f"Appending to the file {x}\n") fh.close() except PermissionError: print(f"You do not have the rights to access the file {x}") except IsADirectoryError: print(f"{x} is actually a directory") except: print(f"An undefined error accessing the file {x}") else: print (f"Added to the file {x} successfully")

Page 17: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Example

● Program runs and exceptions are captured and bypassed

● Program completes● Valid file is edited.

$ ./write_to_files.py user_file_dir is actually a directoryYou do not have the rights to access the file root_file.txtAdded to the file user_file.txt successfully

$ cat user_file.txt User file Appending to the file user_file.txt

$ sudo cat root_file.txt Root file

Page 18: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

raise()

● Stops program and throws up error.$ cat write_to_files.py#! /usr/bin/env python3

file_list = ['user_file_dir', 'root_file.txt', 'user_file.txt']

for x in file_list: try: fh = open(x, "a") fh.write(f"Appending to the file {x}\n") fh.close() except PermissionError: raise Exception(f"No rights to access the file {x}") except IsADirectoryError: raise Exception(f"{x} is actually a directory") except: print(f"An undefined error accessing the file {x}") else: print (f"Added to the file {x} successfully")

Page 19: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

raise()

● Stops program and throws up error– Points to error line number– Returns error message to the terminal.

$ ./write_to_files.py Traceback (most recent call last): File "./write_to_files.py", line 7, in <module> fh = open(x, "a")IsADirectoryError: [Errno 21] Is a directory: 'user_file_dir'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "./write_to_files.py", line 13, in <module> raise Exception(f"{x} is actually a directory")Exception: user_file_dir is actually a directory

Page 20: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Exercise 12

Page 21: Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading the file, line by line ** This is a test file that I want to write to Some more

Thank you