# Compute the number of words, lines and characters in a file. The results # will be saved in a new file. Both file names will be command line parameters. import sys # Check the command line parameters and open the files if len(sys.argv) != 3: print("You must start this program with 2 command line parameters.") print("") print(sys.argv[0], " ") quit() inf = open(sys.argv[1], "r") outf = open(sys.argv[2], "w") # Count the words, lines and characters in the input file num_lines = 0 num_chars = 0 num_words = 0 line = inf.readline() while line != "": num_lines = num_lines + 1 num_chars = num_chars + len(line) # Use split to generate a list of words, then compute the length of the # list to get the number of words num_words = num_words + len(line.split()) # Read the next line from the file line = inf.readline() # Save the number of words, lines and characters in the output file outf.write("Lines: " + str(num_lines) + "\n") outf.write("Words: " + str(num_words) + "\n") outf.write("Chars: " + str(num_chars) + "\n") # Close the files inf.close() outf.close()