#---------------------------------------------------------------------- # Techniques for reading text from files. # # Copyright (C) April 26, 2017 -- Dr. William T. Verts #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Technique #1: Read the entire file in as a single string # The characters are then counted into a dictionary. #---------------------------------------------------------------------- def Main1(): Filename = pickAFile() # Get a file name Infile = open(Filename, "r") # Open a file handle for reading X = Infile.read() # Read entire file in as one string Infile.close() # Close file handle print X # Print the string (the whole file) print len(X) # Prints the number of characters in the string X D = {} # Build a dictionary containing the counts for CH in X: # of every character in the string/file. if not (CH in D): D[CH] = 0 # First check to see if the character is in the dictionary, initialize if not D[CH] = D[CH] + 1 # Increase the count # print D # Print the result return #---------------------------------------------------------------------- # Technique #2: Read file into a list, one line of text per list entry. # Note that line-breaks (\n) are present at the end of each string. #---------------------------------------------------------------------- def Main2(): Filename = pickAFile() # Get a file name Infile = open(Filename, "r") # Open a file handle for reading X = Infile.readlines() # Read file in as list of strings (one line per string, including newline characters) Infile.close() # Close file handle print X # Print the list print len(X) # Print the number of items in the list (the number of lines in the file) return #---------------------------------------------------------------------- # Technique #3: Same as Technique #2, except that trailing line-breaks # are stripped out. File is then capitalized and written out to a # new file. #---------------------------------------------------------------------- import string def Main3(): Filename = pickAFile() # Get a file name Infile = open(Filename, "r") # Open a file handle for reading X = Infile.readlines() # Read file in as list of strings (one line per string), including newline characters Infile.close() # Close file handle X = [L.rstrip("\n") for L in X] # Strip off trailing newlines X = [string.upper(L) for L in X] # Capitalize all the strings (could be combined with previous statement) print X # Print the list print len(X) # Print the number of items in the list (the number of lines in the file) Dot = string.find(Filename,".") # Use string slicing to insert "NEW" Filename = Filename[:Dot] + "NEW" + Filename[Dot:] # right before the dot in the filename. Outfile = open(Filename,"w") # Open a file handle for new file for writing for L in X: # Outfile.write(L+"\n") # Write out each line to the file, restoring line breaks Outfile.close() # Close file handle return