# # Compute the number of lines, words and characters in a text file. # The name of the file will be proivded as a command line argument. # import sys # Retrieve the name of the file from the command line. if len(sys.argv) == 1: # Read the input from the keyboard, write the output to the screen inf = sys.stdin outf = sys.stdout elif len(sys.argv) == 2: # Read the input from a file, write the output to the screen fname = sys.argv[1] # Open the file for reading. inf = open(fname, "r") # Output goes to the screen outf = sys.stdout elif len(sys.argv) == 3: # Read the input from a file, write the output to a file fname = sys.argv[1] out_fname = sys.argv[2] # Open the file for reading. inf = open(fname, "r") # Open the file for writing. outf = open(out_fname, "w") else: # Too many command line arguments were provided. print("The program must be started with 2 or fewer command line arguments.") print() print("python wc.py [input_file] [output_file]") quit() # Process the file and count the number of lines, words and characters. lines = 0 words = 0 chars = 0 line = inf.readline() # Read the first line from the file while line != "": lines = lines + 1 words = words + len(line.split()) chars = chars + len(line) line = inf.readline() # Read the next line from the file # Close the file. inf.close() # Display the results. #print(f"lines: {lines}") #print(f"words: {words}") #print(f"characters: {chars}") outf.write(f"lines: {lines}\n") outf.write(f"words: {words}\n") outf.write(f"characters: {chars}\n") outf.close()