1,760
edits
Changes
no edit summary
<font color='red'>
'''** DO NOT USE - TO BE UPDATED FOR CENTOS 8.0 **'''
</font>
= LAB OBJECTIVES =
:This lab will introduce object oriented programmingSo far, using classes you have created Python scripts to prompt a user to create objectsinput data from the keyboard. When creating Python scripts, and reading/writing you may also need to be able to filesprocess large volumes of information, or store processed data for further processing.:The first investigation in this lab will focus on file management, opening files, saving data to files, and reading files. :'''NOTE:''' Since many tasks that system administrators perform deal with files, this is a crucial skill to understand. :It is very important to provide logic in your Python script in case it '''encounters an error'''. An example would be an invalid path-name or trying to close a file that is already closed. The second investigation in this lab will cover object oriented programming. Objects are primarily used look into how the Python interpreter '''handle errors''' (commonly referred to store data as "exception handling") at run time, and learn how to write Python codethat will run gracefully even when problems occur during program execution.
== PYTHON REFERENCE ==
= INVESTIGATION 1: Working with Files =This first investigation :You will cover the ability now learn how to write Python scripts in order to open text files on the system, to read the contentswithin a text file, store to process the contents, and finally to write the processed contents back into a file. This is a These operations are very common practice in programming, and are used extensively in programming. Examples of file operations would include situations such as logging output, logging errors, reading/and creating configuration files, /temporary files, and more. Files are accessed through the use of file objects, an object is a storage location which stores data in the form of attributes(variables) and methods(functions). Creating our own objects will be covered in investigation 3etc.
:Files are accessed through the use of '''file objects'''. An '''object''' is a '''storage location''' which stores data in the form of '''attributes''' (variables) and '''methods''' (functions). Creating our own objects will be covered later in investigation 3. == PART 1 - Reading Data From Files ==
:'''Perform the Following Steps:'''
</source>
Hello World
This is the second line
Third line
Last line
</source><br>In order to read data from a text file, we need to create an object that will be used to access the data in a file. In some programming languages (like C) this is called a file descriptor, or a file pointer. In Python, it's an '''object'''.<br><br>::#Now lets write some python code to open this created file for reading.We will define and object called '''"f"''' in order to help retrieve content from our text file. Issue the following:<source lang="python">
f = open('data.txt', 'r')
</source><br>The '''open()''' function takes two string arguments: a path to a file, and a mode option (to ask for reading, writing, appending, etc). The ''open()'' function will return a file object to us, this file object will allow us to read the lines inside the file.<br><br>
:#Here are the most useful functions for text file manipulation:<source lang="python">
f.read() # read all lines and stores in a string
f.readlines() # read all lines and stores in a list
f.readline() # read first line, if run a second time it will read the second line, then third
f.close() # close the opened file
</source>
read_data = f.read()
print(read_data)</source>::#Finally <br>After you have completed accessing data within a file, you should '''close ''' the file in order to free up the computer resources. First lets check It is sometimes useful to see if first confirm that the file is already closedstill open prior to closing it.But really you should know - it's your code that would have opened it:<source lang="python">f.closed # This object attribute will give true if the file is closed and false if open
f.close() # This method will close the file
f = open('data.txt', 'r') # Open file
read_data = f.read() # Read from file
f.close() # Close filef.closed # Confirm file is closed</source>::#Another way to read data from a file is using the with statement. The advantage here is that it will automatically close() the file when complete:<source lang="python">with open('data.txt', 'r') as f: # Open file read_data = f.read() # Read from filef.closed # Confirm file is closed</source>::#Next lets read the data<source lang="python">read_data</source>::#This displays in this case contains the data from the file in a single <u>long </u> string. The end of each line in the file will show a the special character ''''\n'''' which represents the '''newline character ''' in a file used to separate lines (or records in a traditional "flat database file"). Split It would be convenient to '''split''' the line on the new-line characters, so more inspection each line can be done on stored as an item in a single line at list.<br><br>:#Store the contents of our file into a time.list called '''list_of_lines''':<source lang="python">dir(read_data)help(read_data.split)
read_data.split('\n') # Returns a list
list_of_lines = read_data.split('\n') # Saves returned list in variable
print(list_of_lines)</source>::#The <br>Although the above sequence works, but itthere are '''functions''' and '''methods'''s not the best way we can use with '''our object (called "f")''' to get place lines from our file into a '''list of lines'''. The man benefit above This would help to reduce code and is that the considered a more common method to store multiple lines can be split in any way desired(on spaces, on periods, etc)or records within a list. The easiest way <br><br>:#Try these two different means to just get store data into a list of all lines can be done using the file object and it's methods.more efficiently:<source lang="python"># METHOD 1:
f = open('data.txt', 'r')
method1 = list(f)
f.close()
print(method1) # METHOD 2:
f = open('data.txt', 'r')
method2 = f.readlines()
f.close()
</source>
=== Create a Python Script Demonstrating Reading Files ===
#!/usr/bin/env python3
</source>
::*This Python script will read the same file ('''data.txt''') that you previously created::*The '''read_file_string() ''' function should return a string:::*The '''read_file_list() ''' function should return a list:::*The '''read_file_list() ''' function must remove the new-line characters from each line in the list:::*'''Both functions must accept one argument ''' which is a string:::*The script should show the exact output as the samples:::*The script should contain no errors
python3 lab5a.py
Hello World
</source>
import lab5a
file_name = 'data.txt'
print(lab5a.read_file_string(file_name))# Will print 'Hello World\nThis is the second line\nThird line\nLast line\n'print(lab5a.read_file_list(file_name))# Will print ['Hello World', 'This is the second line', 'Third line', 'Last line']
</source>
cd ~/ops435/lab5/
pwd #confirm that you are in the right directory
ls CheckLab5.py || wget matrix.senecachttps://raw.ongithubusercontent.cacom/~acoatleySeneca-willisCDOT/ops435/master/LabCheckScripts/CheckLab5.py
python3 ./CheckLab5.py -f -v lab5a
</source>
<br><br>
== PART 2 - Writing To Files ==
f = open('file1.txt', 'w')
</source>
:#To confirm that the new file now exists and is empty, issue the following shell command:#<source lang="bash">ls -l file1.txt</source>To add lines of text to the file, you can use the '''write() ''' method for the '''file object'''. For safe file management, always Typically you end every line in a text file with a the special character ''''\n'''' to represent a "new line". Multiple lines may also be placed inside a single write, operation: simply put the special character ''''\n'''' wherever a line should end.<br><br>:#Try adding multiple lines:<source lang="python">
f.write('Line 1\nLine 2 is a little longer\nLine 3 is too\n')
</source>::#Once the '''write() ''' method has been runcompleted, the final step would be is to '''close() ''' the file. The file MUST be closed properly or else data will not consistently be written to the file. '''NOTE: Not closing a file can lead to corruption corrupted or not changes being mademissing file contents. ''':<br><source lang="python">
f.close()
</source>
f = open('file2.txt', 'w')
f.write('Line 1\nLine 2 is a little longer\nLine 3 is tooas well\n')
f.write('This is the 4th line\n')
f.write('Last line in file\n')
f.close()
</source>
</source>
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:#View the 25px"|Make Backup Copies of Your Data Files|Since you might make a mistake, and accidentally destroy file contents when writing to your file, it is highly recommended to make backup copies of your files prior to running your Python scripts. This can be particularly useful when performing any future assignment involving writing to files.}}</blockquote><blockquote style="margin-left:35px;">{{Admon/caution|style="padding-left:25px"|Make Backup Copies of ALL your files|Since you are now writing code that opens files for writing you may accidentally truncate the file1wrong file (like your assignment file, for example). Make regular backups of all your work.txt Just copy it to make sure it has a USB stick or if you're bored - learn version control.}}</blockquote><br><ol style="margin-left:80px;"><li value="7">Issue the original data following shell commands to backup both of your newly-created files and has not been changedconfirm backup:<source lang="pythonbash">%cat cp file1.txt file1.txt.bkcp file2.txt file2.txt.bkLine 1ls -l file* Line 2 is a little longer</source></li><li>Let's demonstrate what can happen if you perform an incorrect write() operation:<source lang="python">Line 3 is too f = open('file2.txt', 'w')
</source>
f = open('file1.txt', 'a')
f.write('This is the 4th line\n')
f.write('Last line in file\n')
f.close()
</source> ::#<source lang="bash">cat file1.txt</source>The final point thing to make consider when writing to files is to make sure certain that the values being written are '''strings'''. This means that before trying to place integers, floats, lists, or dictionaries into a file, first either convert the value using '''str() ''' function or extract the specific strings from items in the list. <br><br></li><li>In this example we convert a single number and all the numbers in a list to strings before writing them to a file:<source lang="python">
my_number = 1000
my_list = [1,2,3,4,5]
f.write(str(num) + '\n')
f.close()
</source></li>::#View the contents of the file3.txt to make sure <li>Confirm that the '''write data ()''' operation was saved.successful<source lang="pythonbash">%cat file3.txt 1000 1 2 3 4 5 </source></li></sourceol>
=== Create a Python Script Demonstrating Writing to Files ===
def append_file_string(file_name, string_of_lines):
# Takes two strings, appends the string to the end of the file
def copy_file_add_line_numbers(file_name_read, file_name_write):
# Takes two strings, reads data from first file, writes data to new file, adds line number to new file
</source>:# '''Replace''' the main section of your Python script near the bottom with the following:<source lang="python">
if __name__ == '__main__':
file1 = 'seneca1.txt'
copy_file_add_line_numbers(file2, file3)
print(read_file_string(file3))
</source> ::'''append_file_string():''':::#Takes '''two string arguments''':::#'''Appends''' to the file(Argument 1) all data from the string(Argument 2)::'''write_file_list():''' :::#Takes two arguments: a '''string''' and a '''list''':::#'''Writes''' to file(Argument 1) all lines of data found in the list(Argument 2)::'''copy_file_add_line_numbers():''':::#Takes two arguments: '''Both are files path-names''' (which happen to be strings):::#'''Reads''' all data from first file(Argument 1), and writes all lines into second file(Argument 2) '''adding''' line numbers:::#Line numbers should be added to the '''beginning''' of each line with a colon next to them(see sample output below for reference):::#'''Hint:''' Use an extra variable for the line number :::'''Sample Run 1:'''<source>rm seneca1.txt seneca2.txt seneca3.txt./lab5b.py First LineSecond LineThird Line Line 1Line 2Line 3 1:Line 12:Line 23:Line 3
</source>
:::'''append_file_string()'''::::#Takes two string arguments::::#Appends to the file(Argument 1) all data from the string(Argument Sample Run 2):::'''write_file_list()''' ::::#Takes two arguments, a string and a list::::#Writes to file(Argument 1run second time) all lines of data found in the list(Argument 2):::'''copy_file_add_line_numbers()'''::::#Takes two arguments, both strings, both filesnames::::#Reads all data from first file(Argument 1), writes all lines into secon file(Argument 2) adding line numbers::::#Line numbers should be added to the beginning of each line with a colon next to them(see sample output)::::#Hint: review len() and range() functions from lab 3 and lab 4 ::::'''Sample Run 1:'''<source lang="python">
python3 lab5b.py
First Line
Second Line
Third Line
First Line
Second Line
</source>
import lab5b
file1 = 'seneca1.txt'
lab5b.read_file_string(file1)
# Will print 'First Line\nSecond Line\nThird Line\nFirst Line\nSecond Line\nThird Line\n'
lab5b.write_file_list(file2, list1)
lab5b.read_file_string(file2)
# Will print 'Line 1\nLine 2\nLine 3\n'
lab5b.copy_file_add_line_numbers(file2, file3)
lab5b.read_file_string(file3)
# Will print '1:Line 1\n2:Line 2\n3:Line 3\n'
</source>
cd ~/ops435/lab5/
pwd #confirm that you are in the right directory
ls CheckLab5.py || wget matrix.senecachttps://raw.ongithubusercontent.cacom/~acoatleySeneca-willisCDOT/ops435/master/LabCheckScripts/CheckLab5.py
python3 ./CheckLab5.py -f -v lab5b
</source>
<br><br>
= INVESTIGATION 2: Exceptions and Error Handling =
:Running into errors in programming will be a common occurrence. You should expect that it will happen for any code that you write. In python, when an error occurs, the python runtime raises an '''exception'''. This section will teach you to catch these exceptions when they happen and to allow the program to continue running, or to stop program execution with a readable error message.
== PART 1 - Handling Errors ==
print('5' + 10)
</source>::#Immediately You should get an exception error similar to the following error occurs:<source lang="python">
---------------------------------------------------------------------------
try:
print(5 + 10)
except TypeError:
print('not At least one of the values is NOT an integer')
15
</source><br>You should notice that since there was NOT an error, the Python script performed the required task.<br><br>::#TypeError ExceptionThe following code handles an exception error to provide user-friendly feedback that at least one of the values is not an integer:<source lang="python">
try:
print(5 + 'ten')
except TypeError:
print('not At least one of the values is NOT an integer')
</source>
f = open('filethatdoesnotexist', 'r')
</source>
try:
f = open('filethatdoesnotexist', 'r')
except FileNotFoundError:
print('no file found')
</source>::#<br>Multiple exceptions can also be caught at the same time, such as does not exist, is a directory, or we don't have permission. Try <br><br>:#To test out the error handling code (previously issued), try removing permissions from the file, or creating specify a directory instead of a regular file, and opening then try to open it. :<source lang="python">
try:
f = open('filethatdoesnotexist', 'r')
f.write('hello world\n')
f.close()
except (FileNotFoundError, PermissionError, IsADirectoryIsADirectoryError):
print('failed to open file')
</source>
try:
f = open(abc, 'r')
print('unknown error occured')
raise
</source>::#When catching multiple exceptions, make sure certain to catch the <u>lowest </u> ones on contained in the exception-hierarchy first. If For example, if you put 'Exception' first, both 'OSError' and 'FileNotFoundError', would never get caught.<br><br>'''TIP::#''' In python it's usually best to 'try:' and 'except:' code rather than to try and determine attempt to anticipate everything that could go wrong with logic and '''if ''' statements. For example, instead of checking to see if a file exists and we have read permissions, it can be better to just try and read the file and fail and catch any errors with 'OSError'.
=== Create a Python Script Which Handles Errors ===
#!/usr/bin/env python3
python3 lab5c.py
15
</source>
import lab5c
cd ~/ops435/lab5/
pwd #confirm that you are in the right directory
ls CheckLab5.py || wget matrix.senecachttps://raw.ongithubusercontent.cacom/~acoatleySeneca-willisCDOT/ops435/master/LabCheckScripts/CheckLab5.py
python3 ./CheckLab5.py -f -v lab5c
</source>
<br><br>
:'''Have Ready to Show Your Instructor:'''
::<span style="color:green;font-size:1.5em;">✓</span> xOutput of: <code>./CheckLab5.py -f -v</code>::<span style="color:green;font-size:1.5em;">✓</span> x:Output of:<span style="color:green;font-size:1code>cat lab5a.py lab5b.py lab5c.5em;">✓py</spancode> Lab4 logbook notes completed = LAB REVIEW = Practice For Quizzes # What is the purpose of a '''file object'''?# Write a Python command to '''open''' the text file called '''customers.txt''' for read-only operations.# Write Python code to efficiently store the contents of the file in question #2 as a large string (including new-line characters) called '''customer-data'''.# Write Python code to store the contents of the file in question #2 as a list, Tests, Midterm & Final Exam =removing the new-line characters.# What is the purpose of '''closing''' an open file? Write a Python command to close the file opened in question #2.# Write the Python command to confirm you successfully closed the '''customers.txt''' file in question #5. What is the returned status from that command to indicate that the file has been closed?# What is the difference between opening a file for '''writing''' data as opposed to opening a file for '''appending''' data? What can be the consequence if you don't understand the difference between writing and appending data?# Write a Python command to open the file '''customer-data.txt''' for writing data.# Write a Python command to save the text: '''customer 1: Guido van Rossum''' (including a new-line character) to the opened file called '''customer-data.txt'''# xBriefly explain the process writing a list as separate lines to an open file.# xWhat is the purpose of '''handling''' exception errors?# xWrite a Python script to prompt a user for the name of the file to open. Use exception error handling to provide an error message that the specific file name (display that exact name) does not exist; otherwise, open the file for reading and display the entire contents of the file (line-by-line). [[Category:OPS435-Python]]