# This block will open a file for reading, # read in the entire file using file.read() # and print out the entire file file1 = open('test1.txt','r') print file1.read() # This block, using variable file2 will read # a file one character at a time, and print it # to the screen file2 = open('test1.txt','r') while 1: # while true char = file2.read(1) # just one byte if not char: break # jump out of the loop print char # prints each character on its own line # This block, using variable file3 will read # a file one character at a time, and print it # to the screen - like 2 space the output lines file2 = open('test1.txt','r') while 1: # while true char = file2.read(1) # just one byte if not char: break # jump out of the loop print char, # prints character followed by a space # use a for loop : read() function will read in the # whole file at once, but the for statement prints # each character one at a time print 'For loop' for char in open('test1.txt','r').read(): print char # use a while loop to read the file one line at a time # the output will still show one character per line print 'Read line at a time' file5 = open('test1.txt','r') while 1: line = file5.readline() # get one line if not line: break # test to see of we read a line print line, # without , it adds crld after each line # read files in chunks / blocks. Here read 12 bytes at a time print 'read blocks (size 12)' file6 = open('test1.txt','rb') while 1: chunk = file6.read(12) if not chunk: break print chunk, # you will see a space after each block # other examples, some read only when a line is not already in memory for line in open('test1.txt').readlines(): print line # reads all lines at once for line in open('test1.txt').xreadlines(): print line # reads line as needed for line in open('test1.txt'): print line # reads as needed #promt the use for a file to open and process f = raw_input("\nExample:Prompting for a file name" "\n \n Please type in the path to your file and press 'Enter': ") file7 = open(f, 'r') while 1: line = file7.readline() # get one line if not line: break # test to see of we read a line print line, # without , it adds crld after each line