Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading...
Transcript of Python Programming · This is a test file that I want 2 write 2 Some more text finished. ** Reading...
Python Programming
Dr Diarmuid Ó Briain
Files and databases
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
Writing to files
$ ./write2file.py
$ cat file.txt This is a test filethat I want to write toSome more textfinished.
Modesr Readw Writea Append
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.
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>
Interfacing with databases
● SQLite Database Browser
Exercise 11
Handling Errors
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
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
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
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
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
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
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")
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
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")
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
Exercise 12
Thank you