Sue Inn Chng
The University of 1
Files – Information Storage
Copyright By PowCoder代写 加微信 powcoder
– Filescanstoreinformation–text,images,binarydata.
– Unix/linux tool called file that can scan the contents of a file and determine its type. Example:
– file hello.py
– file turingprof.gif
– GotoEdLessonanddoPart1. – Identifyexamplesoffilesthatare:
• ASCII text?
• Python script? • gif image
– Howdoyouinspectthefilekrusty.pyinsidefoldera1? The University of 2
Files – Location
– Filesareorganizedintodirectories(alsoknownasfolders).
– Working directory – where you are currently at!
– Astringlike’/home’thatidentifiesafileordirectoryiscalleda path.
– Twotypesofpaths:
– Relative path relates to the current directory. Example:
• Referring to folder: a1
• Referring to file: hello.py
– Absolute path does not depend on the current directory and
The University of 3
begins with /. Example:
• Referring to folder: /home/a1
• Referring to file: /home/hello.py
Exercise – Relative and Absolute Path
– Statewhereiscalzone.jpgusing:
– relative path.
– absolute path.
The University of 4
Revision: Files – Location
– RecallfromWeek1: – pwd
– dir – cd
The University of 5
Guess what I am!
– The os module provides functions for working with files and directories.
– WhereamI?os.getcwd()
– Getalistoffilesandfoldersinpath:os.listdir(path)
– GotoEdLessonanddoPart2.
– Files/foldersIRL.Manythingscangowrong: – Pathgivenbyuserdoesnotexist
– Nosuchfileordirectory
– Whatwillhappenifyourprogramdoesnotspecifywhattodo in these cases?
The University of 6
File Input without Exception Handling
– Write a program to read the number stored in the file called numbers.txt. This file should contain only one integer. File path is provided as a command line argument.
– Anything that can go wrong will go wrong. List all the possible exceptions that can happen during the execution of this program IRL.
– Go to Ed Lesson and run the program for each given case. The University of 7
Exception syntax
– try a piece of code that contains potential rare error
– If the rare error occurs a new exception is generated. raise
– Theexceptioniscaughtusingexceptandhandled
– Following the try, error or not, more code can be executed with a block finally.
The University of 8
finally Block
– Will execute regardless if the try
block raises an error or not.
– Useful to define clean-up actions that must be executed under all circumstances.
– The optional finally block is always executed at the end of the except region:
– Afterthetryblockcompletes successfully,
– Orafteraexceptblockis executed.
The University of 9
Concrete Exceptions
– Goodpracticetostructureexceptblockswithincreasing generality.
– These are the exceptions that are usually raised:
– https://docs.python.org/3/library/exceptions.html#concrete-exceptions – Commonexceptionswehaveencountered:
The University of 10
• TypeError e.g. 2 + “2”
• ValueError e.g. int(“a”)
• ZeroDivisionError e.g. 1/0
• IndexError e.g. sys.argv[99999] • SyntaxError e.g. print(“Hello) • NameError e.g. print(hello)
File Input with Exception Handling
– GotoEdLessonandruntheprogramforeachgivencase. – Did you catch all the exceptions?
The University of 11
Text Files IRL
– Filecontainsmanydifferentpartsbutmayalsocontaincontents that you do not expect.
– Beforeyoucanprocessthecontentsinyourprogram,thefile contents must be loaded into memory for the program to do useful work.
– Example: 2D point locations.
The University of 12
Exercise: 2D Points Locations
– Writeaprogramtoextractallthe2Dpointdatae.g.(x,y)of exactly 20 locations from a given file.
– Thefiles:
• points_perfect.txt
The University of 13
• points_missing.txt
• points_horror.txt
• points_non_numbers.txt
– Theplan:
1. Read each line and load into memory.
2. Check contents of each line:
• If valid 2D points, store as a tuple e.g. (x, y). • If not valid, skip.
Exercise: 2D Points Locations (Step 1)
Review the codes and answer these questions:
What is the data type of these variables:
Call function read_points() with argument points_perfect. What will happen?
Which variable contains the contents read from file? Trace this variable during the execution of the program.
– points – infile
The University of 14
Exercise: 2D Points Locations (Step 2)
Review the codes and answer these questions:
What are the values in tokens if line
Identify which tokens in Q1 will throw ValueError exception?
takes on these values:
– “happy camper”
– “12, 40.5”
– “35, lol”
– “10, 32, 55”
The University of 15
Exercise: 2D Points Locations (PIAT)
– ExecutethefilePointFileReader.pyusingeachofthe given files.
– Observetheoutput.
The University of 16
Reading This Week
– Chapter9and14.Downey,A.B.(2015).ThinkPython:Howto Think Like a Computer Scientist (2e ed.). O’ , Incorporated.
– Chapter1.5.RedirectionandPiping.Sedgewick,R.,Wayne, K., & Dondero, R. (2015). Introduction to programming in Python: An interdisciplinary approach. Addison- .
The University of 17
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com