Python 101 Dr. Bernard Chen University of Central Arkansas PyArkansas
Files File is also one of built-in type in Python The built-in OPEN function creates a Python file object, which servers as a link to a file After calling open, you can read and write the associated external file
Common FILE operations Input=open(‘file_name.txt’, ‘r’) Output=open(‘file_name.txt’, ‘w’) Input.readlines() Input.close(); Output.close()
Split() function >>> string= ‘a b c d e’ >>> string.split() ['a', 'b', 'c', 'd', 'e']
File in Action Let’s try to read in a file!!
File in Action input=open('file.txt','r') all=[] for line in input.readlines(): temp=line.split() all.append(temp)
File in Action Then we can calculate the average score for each student
File in Action for i in range(len(all)): sum=0.0 for j in range(1,len(all[i])): sum=sum+int(all[i][j]) average=sum/5 print average
Python Official Sites Python Tutorial Python Official Site Download Python Latest Version