Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

  1. Type all the information from script1704.py shown below. Take your time and
    avoid any typographical errors:


Click here to view code image


# script1704 - Open a File
# Written by
#
#####################################################
#
################## Functions ########################
#
def get_file_name (): #Get file name
print ()
#
try:
file_name=input("Please enter file to open: ")
print ()
return file_name
#
except KeyboardInterrupt:
print ()
print ("Script terminating....")
print ()
exit ()
#
except:
print ()
print ("An error has occurred.")
print ("Script terminating...")
print ()
exit ()
#
#
def open_it (file_name): #Open file name

my_file=open(file_name,'r')
print ("File", file_name, "opened successfully!")
my_file.close()
#
############## Mainline #############################
#
def main ():
file_name = get_file_name ()
open_it (file_name)
#
############ Call the Main Function ###################
#
main()
Notice that the only try except statement block is for entering information into
the script in the get_file_name function.


  1. Save the editor contents and exit the editor.

  2. Before you test the script, you need to create a little file for the script to open, so at
    the command-line prompt, type echo "I love my Raspberry Pi" >>
    testfile and press Enter.

  3. Test your script by typing python3 py3prog/script1704.py and pressing

Free download pdf