File I/OInput/Output•How have you done i/o?•Why use files?•We'll be talking about text filesFile Input•Open a file on disk•Read from the file•Close the fileOpen a file on diskin_file = open(“filename”, “r”) •filename is the name of the file–filename can be relative or absolute–relative starts looking the current directory as shown above–absolute starts at top of file system–“/home/srollins/myfile.txt”•r indicates that we will read the file – not change it•Returns a file object on which you can call methodsRead from the file•Several options for reading from fileS = in_file.read() #read entire file into string SS = in_file.read(N) #read N bytes into string SS = in_file.readline() #read next lineL = in_file.readlines() #read entire file into list of strings•Each call changes the position in the fileRead from the filewhile 1:line = in_file.readline()if not line:breakprint linewhile 1:char = in_file.read(1)if not char:breakfor line in in_file:print linein_file.close() #make sure to close the file!File Output•Open a file on disk•Write to the file•Close the fileoutfile = open(“ myfile.txt” , “ w” ) #w for write outfile.write(“ this is the info i need to store” )outfile.close()Exercises1. Implement a program to open the file “dracula.txt”, count the number of lines on which the word “vampire” appears, and write the result to a new
View Full Document