340 likes | 433 Views
File I/O. Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012. File. Files: named storage compartment on your computer that are managed by operating system The built-in “open” function creates a Python file object, which serves as a link to a file in your computer.
E N D
File I/O Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012
File • Files: named storage compartment on your computer that are managed by operating system • The built-in “open” function creates a Python file object, which serves as a link to a file in your computer
Open Function • After calling open, you can read or write the associated external file • Two major types of open file function: • Read file (‘r’) • Write file (‘w’)
Read/Write file • Open function take two variables, first on is the file name you want to deal with, another one is read or write of the file • input = open ('file1.txt','r') Variable name Keyword file name read file • output = open (‘output_file.txt’, ‘w’) Variable name Keyword file name write file
Read/Write file • In the end of the program, remember to close the file via close() function • Input.close() • Output.close()
Read File • After connect with the file through open function, you need “readlines()” to read the contents in the file • readlines() is the function that read entire file into list of line strings
Read File input = open ('file1.txt','r') input.readlines() • But this is not good enough, because the contents we read is in text format, we need to convert it into numbers and store those in a list, so that we can do some computations on those numbers
Read File • After we read in those files into list ‘all’, we can easily calculate average, max, min…
Class Practice • Download file1 into the Python folder • Read in the file and print out the max value
Write file • We have a “write” function for write things on a file • Things you want to write MUST be string, so if you want to write a number, you have to convert it by str() output = open (‘output_file.txt’, ‘w’) output.write(“Hello World!!!”) output.write(str(12))
Write file • write number form 0 to 10 into a file output = open (‘output_file.txt’, ‘w’) for i in range(11): output.write(str(i)) output.write(‘\n’) output.close()
Class Practice • Write the following half pyramid into a new created file named “pyramid.txt” * ** *** **** *****
Read File • Now, think about different file type we have…
Read in File2 • Since all numbers are in one line, we cannot read this file like we did in file1 • We need to “separate” the numbers through space
Read in File2 • As the result, we need the function “split(str)” • This method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified)
split() examples >>> sentence = "the cat sat on the mat" >>> print sentence.split() ['the', 'cat', 'sat', 'on', 'the', 'mat'] >>> sentence = "the,cat,sat,on,the,mat“ >>> print sentence.split(',') ['the', 'cat', 'sat', 'on', 'the', 'mat']
Class Practice >>> sentence = "the cat sat on the mat" >>> print sentence.split(‘t’)
Read in File2 input=open('file2.txt','r') for line in input.readlines(): all=line.split() for i in range(len(all)): all[i]=int(all[i])
2D list: lists inside of list • Here’s the way to create a 2D list (Just like what we saw last week) aa=[1,2,3] bb=[4,5,6] cc=[7,8,9] matrix=[] matrix.append(aa) matrix.append(bb) matrix.append(cc)
Access 2D list • With one index, you get an entire row: >>> matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> matrix[0] [1, 2, 3] >>> matrix[1] [4, 5, 6] >>> matrix[2] [7, 8, 9]
Access 2D list • With two index, you get a item within the row: >>> matrix[0][0] 1 >>> matrix[0][1] 2 >>> matrix[1][1] 5 >>> matrix[1][2] 6 >>> matrix[2][2] 9
Len() function on Matrix • len() function can tell the size of the list By the same token: >>>len(matrix) 3 >>>len(matrix[0]) 3
Matrix • If we have another matrix looks like: >>> matrix [[10, 20, 30, 40, 50, 60, 70, 80], [11, 12, 13, 14, 15, 15], [15, 25, 35, 45, 55, 65, 75, 85, 95]] >>> matrix[0] [10, 20, 30, 40, 50, 60, 70, 80] >>> matrix[1][1] 12 >>> matrix[0][8] error
Matrix >>> len(matrix) 3 >>> len(matrix[0]) 8 >>> len(matrix[1]) 6 >>> len(matrix[2]) 9
Append function • If we have a matrix=[[1,2,3],[4,5,6],[7,8,9]] after >>> matrix.append(3) the matrix looks like: therefore, >>> matrix[3] 3
Append function • If we have a matrix=[[1,2,3],[4,5,6],[7,8,9]] after >>> matrix[1].append(3) the matrix looks like: therefore, >>> matrix[1][3] 3
Append function • If we have a matrix=[[1,2,3],[4,5,6],[7,8,9]] after >>> matrix.append([1,2,3]) the matrix looks like: therefore, >>> matrix[3] [1,2,3]
Read File3 input=open('file3.txt','r') matrix=[] for line in input.readlines(): matrix.append(line.split())
Print out the average score of each student input=open('file3.txt','r') matrix=[] for line in input.readlines(): matrix.append(line.split()) for i in range(len(matrix)): sum=0 for j in range(len(matrix[i])): sum+=int(matrix[i][j]) avg=sum/len(matrix[i]) print avg
Write the average score of each student to file input=open('file3.txt','r') output=open('avg.txt','w') matrix=[] for line in input.readlines(): matrix.append(line.split()) for i in range(len(matrix)): sum=0 for j in range(len(matrix[i])): sum+=int(matrix[i][j]) avg=sum/len(matrix[i]) print avg output.write(str(avg)+'\n') input.close() output.close()