# File: deSpacer3.py # Author: Dr. Gibson # Date: 4/10/2017 # Section: N/A # E-mail: k.gibson@umbc.edu # Description: # This file contains python code that opens a file called "spaced.txt", # counts and removes all of the whitespace, prints out the count, # and saves the result to a file called "unspaced.txt" def main(): # open a file for reading (spaced.txt) inFile = open("spaced.txt", "r") # read in the whole thing as a list of strings listOfLines = inFile.readlines() # use nested for loops to iterate over all the strings, counting the # whitespace characters, and adding non-whitespace to a new string count = 0 unspaced = "" for line in listOfLines: # this loop iterates over each line for ch in line: # this loop iterates over chars in a line # if it's a whitespace character, count it if ch == " " or ch == "\t" or ch == "\n": count += 1 # otherwise, append it to a string containing the other characters else: unspaced = unspaced + ch print("There were", count, "spacing characters in the file") # create a new file, by opening it for writing (unspaced.txt) outFile = open("unspaced.txt", "w") # write the new stuff to the file outFile.write(unspaced) # close BOTH files inFile.close() outFile.close() main()