Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Programming Python Programming head_tail = 10 pts, split = 20 pts, and wc

ID: 3889901 • Letter: P

Question

Python Programming

Python Programming head_tail = 10 pts, split = 20 pts, and wc = 15 pts. Write a complete Python program with prompts for the user for the main text file (checks that it exists, and if not, output an error message and stop), for any possible flags (including none), and for any other input that this program may need from the user: split has an option of naming the smaller files head_tail list the first 10 lines (default) and the last 10 lines (default) in order of the given text file flag: -# output # lines instead of default lines Comment: If the file has less than 20 lines (default), output the entire file split flags: split a text file into smaller pieces -# put # lines of text into each output file (defaults = 1000 lines) input: file file to be split (note extension and use it on split files) name file of newfiles (example: name-aa.ext, name-ab.ext, etc.) name may be blank, so the files are: xaa.ext, xab.ext, etc. Comment: Output the name of the file as it is being created wc count characters, lines, and words in a text file output order: lines words characters

Explanation / Answer

Note: Couldn't do the split part.

CODE:

import sys
from itertools import islice

num_lines = 0
num_words = 0
num_chars = 0

filename = input("Enter name of file: ")

try:
fptr = open(filename)
fptr.close()
except FileNotFoundError:
sys.exit("File does not exist")

with open(filename) as fptr:
for line in fptr:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)

try:
flag = int(input("Enter flag number (0 for default): "))
if flag < 0:
sys.exit("Entered flag should be >= 0")
except ValueError:
sys.exit("Entered flag is not an integer")

if flag == 0:
flag = 10

if num_lines < (flag * 2):
with open(filename) as fptr:
print ("printing whole file")
print (fptr.read())
else:
with open(filename) as fptr:
print("HEAD")
for num, line in enumerate(fptr):
if (num > (flag - 1)):
break
print (line[:-1])
print("TAIL")
for num, line in enumerate(fptr):
#print(num)
if (num + (flag + 1) < num_lines - flag):
continue
print (line[:-1])

print()
print("wc")
print(str(num_lines) + " " + str(num_words) + " " + str(num_chars))