CIT 590 Intro to Programming Lecture 6 • Vote in the doodle poll so we can use some fancy algorithm to pair you up • http://doodle.com/rm9ihqe2rfsirrs5 • You have to program in pairs • I sadly still don’t know if we have an odd number of students or an even number. • We don’t know the algorithm yet but it has to satisfy the obvious time constraint Agenda • Files • Try catch except • A module to read html off a remote website Basic file operations • f = open(‘myRandomFile.txt’) • Open(“”) • Default is the read only mode • Open(“”, “w”) • Open the file in the mode that you would like to use it • Read - r • Write - w • Append – a • Opening a file in the ‘r+’ mode if you want to read and write to it at the same time. • Use this one with caution Reading and writing to a file • Read, readline, readlines • Using a while loop to read every single line of a file • Write, writelines • Close() – why should I close a file • Cleaning up • The operating system should close the file, but that behavior is not entirely under your control • Remember that opening a file for writing will remove the old values • fileExperiments.py Tell and seek • Once I have read a file all the way through how do I go back to the start?? • Or in general, how do I mark a point in the file that I now want to come back to. x = f.tell() #do some reading writing etc etc on f f.seek(x) to get back to where we were What file formats are supported? • Text files work best in that they do not come with headers and footers etc • You can always read in binary • Usually if you are dealing with a specific format, you will be using some extra packages Looping through the contents of a file • Instead of using a while loop with a readline, python provides the ability to do a for loop • For line in f will read one single line of the file and assign it to the temp variable line. • Loop until EOF (end of file) The os module • File management is generally being done at the operating system level • In Python if you want to use command prompt like commands ‘import os’ • os.listdir(‘C:\Python27’) • os.rename(‘oldfilename’, ‘newfilename’) Exceptions! Try except • try: Something except error, e: do something with the error. Maybe print some message else: #it was a successful attempt. Now do the real work tryExceptForFiles.py Standard input and output • The sys module gives you access to some built in ‘files’ • The console input is basically just sys.stdin • Similarly the console output is sys.stdout • Sys module has other built in functions like sys.argv to get the command line arguments. • add10ToConsoleInput.py The file sort example from the book • Good example for top down design • fileSort.py Reading from a url • Import urllib • Urllib.urlopen(http://www.google.com) • Only works on a subset of sites. Secure sites will usually not allow you to grab info that easily. • My seas website isn’t particularly secure …. • getAllTAs.py