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

Please help! We have to prompt the user for the name of a file and open it. (If

ID: 3859288 • Letter: P

Question

Please help!

We have to prompt the user for the name of a file and open it. (If the file cannot be opened, you’ll ask the user for another file, looping until you are able to open a file.) ...Below is the prompt

Here is the proj07_utils.py...

NOT SURE IF WHAT I HAVE WRITTEN WILL WORK...at all for inFile block and try block

  

2.1 proj07 utils.py This file has a set of utility functions, several of which are used in multiple of the programs you're required to write. Implement these gradually, as you're testing new versions of the program. Each function has a detailed docstring, which documents how it should work. I have not written unittests for them - but you will be doing some (see below).

Explanation / Answer

Python 2.7 code to to prompt the user for the name of a file and open it. (If the file cannot be opened, you’ll ask the user for another file, looping until you are able to open a file.)

while(True):

print "Enter the filename!"

fname = raw_input()

try:

with open(fname) as fp:

print fname , "Can be opened!"

break;

except IOError:

print "could not open ", fname, ", Please enter valid filename!"

Sample Output:

Enter the filename!
xyz.txt
could not open xyz.txt , Please enter valid filename!
Enter the filename!
abc.txt
could not open abc.txt , Please enter valid filename!
Enter the filename!
out.txt
out.txt Can be opened!

Note : Make sure you are using python 2.7, if you are using python 3.X, then coment below, I will change the code accordingly!

Python 2.7 code for get_file_words() function:

def get_file_words():

while(True):

print "Enter the filename!"

fname = raw_input()

try:

with open(fname) as fp:

print fname , "Can be opened!"

words = []

content = fp.readlines()

for line in content:

tmp = line.split(" ")

for w in tmp:

words.append(w.strip())

return words

except IOError:

print "could not open ", fname, ", Please enter valid filename!"

outlist = get_file_words();

print outlist;

Python 2.7 code for function alpha_only_words(words):

import re

def alpha_only_words(words):

tmp = []

for w in words:

w = re.sub(r'W+', '', w)

tmp.append(w.lower())

tmp = list(set(tmp))

if('' in tmp):

tmp.remove('')

fs = frozenset(tmp)

return fs

words1 = ["FOO", "it's", "don't"]

print words1

print alpha_only_words(words1) , " "

words2 = ["can't", "!*#@", "caNt"]

print words2

print alpha_only_words(words2), " "

words3 = []

print words3

print alpha_only_words(words3), " "

Sample Output:

['FOO', "it's", "don't"]
frozenset(['foo', 'its', 'dont'])

["can't", '!*#@', 'caNt']
frozenset(['cant'])

[]
frozenset([])

Note : Make sure you are using python 2.7, if you are using python 3.X, then coment below, I will change the code accordingly!