12 Pages
Unlock Document

University of Toronto Scarborough
Computer Science
Brian Harrington

Files Our data files are text files which are filled with characters In Python we must open files before we can use them and close them when we are done with them Once a file is opened it becomes a Python object just like all other data Newline Character n A line of a file is defined to be a sequence of characters up to and including a special character called the newline character ninformation about my test file FAcademicCSCA08Weekly Reading Notestesttxt Cinny My examples nothing more to say openfilename r Open a file called filename and use it for readingopenfilename w Open a file called filename and use it for writingopen will return a reference to a file object If the file and the Python program are in the same directory opentesttxt r If not openFAcademicCSCA08Weekly Reading Notestesttxt r Create a variable name for later referencing myfileopentesttxt rmyfileopentesttxt rmyfile ioTextIOWrapper nametesttxt moder encodingcp936 filevariablereadnReads and returns a string of n characters or the entire file as a single string if n is not providedxopentesttxt ryxready CinnynMy examplesnnothing more to sayprinty Cinny My examples nothing more to sayzxreadzBe careful about this one restart the Python shellxopentesttxt ryxread2printy Ci filevariablereadlinenReturns the next line of the file with all text up to and including the newline characterIf the line is longer than n characters only n characters will be returnedxopentesttxt ryxreadliney CinnynYystripnY Cinnyprinty CinnyIf you evaluate it the new line will be represented as n If you print it you will not see the n the new line will just be shownzxreadlinez My examplesn If you apply readline to the same file the second times the next line will be shownmxreadline2m no If I didnt input n nothing more to say will be returned filevariablereadlinesn Returns a list of strings each representing a single line of the file If n is provided then n characters are read but n is rounded up so that an entire line is returnedxopentesttxt ryxreadlines
More Less

Related notes for CSCA08H3

Log In


Don't have an account?

Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Sign up

Join to view


By registering, I agree to the Terms and Privacy Policies
Already have an account?
Just a few more details

So we can recommend you notes for your school.

Reset Password

Please enter below the email address you registered with and we will send you a link to reset your password.

Add your courses

Get notes from the top students in your class.