Read the whole file as a string - Tom Kleen



FilesFile: a collection of data stored on a secondary memory device (magnetic disk, optical disk, magnetic tape, flash memory).Method NameUseExplanationwritefile.write(astring)Add astring to the end of the file. file must refer to a file that has been opened for writing.read(n)file.read()Reads and returns a string of?n?characters, or the entire file as a single string if n is not provided.readline(n)file.readline()Returns the next line of the file with all text up to and including the newline character. If n is provided as a parameter than only n characters will be returned if the line is longer than?n.readlines(n)file.readlines()Returns a list of strings, each representing a single line of the file. If n is not provided then all lines of the file are returned. If n is provided then n characters are read but n is rounded up so that an entire line is returned.Try these with the QB-Stats.txt file.Read the whole file as a stringinfile = open("qb-stats.txt")data = infile.read()#entire file is in a single stringprint(data)#prints all 1979 charactersprint(len(data))#prints 1979items = data.split()#split the dataThe above read command moves the file pointer. If we want to read the file's data again, we need to re-open it:Read the next line from the fileinfile = open("qb-stats.txt")line = infile.readline()# read one line at a timeRead all lines from the fileinfile = open("qb-stats.txt")lines = infile.readlines()#read all lines; returns a list of stringsReading with a while loopline = infile.readline()while line: values = line.split() print('QB ', values[0], values[1], 'had a rating of ', values[10] ) line = infile.readline()infile.close()How it works with a while loopLook at the while loop. The "Boolean" expression for the loop is the variable line. As long as the variable line has a non-zero value (None and the empty string "" are also considered "zero" values (non-True values)). We MUST read something before entering the loop the first time, or we will never get in the loop in the first place. Output filesFrequently in this class, we will be using files for input. But often it is necessary for a program to create an output file, too.To open an output file:outfile = open("filename", "w")The "w" stands for "write" and means that we are going to be writing data to the file. When reading an input file, you can replace the "w" with an "r" (for "read"), but "r" is the default, so it is usually omitted.Sample programoutfile = open("data.txt", "w")for i in range(10000): outfile.write(str(i) + "\n")outfile.close()NOTE: The integer variable i must be converted to a string.NOTE: The output file must be closed. If you omit the close function, you may not have all of your output file saved! ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download