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

This program will be ran through a Python 3 IDE, please use correct formatting a

ID: 3690574 • Letter: T

Question

This program will be ran through a Python 3 IDE, please use correct formatting as such.

Function fileLength(), given to you, takes the name of a file as input and returns the length of the file (You may test your function on any file):

Here is an example of how the function should work:

>>> fileLength('midterm.py')
284
>>> fileLength('idterm.py')
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
    fileLength('idterm.py')
File "/Users/me/midterm.py", line 3, in fileLength
    infile = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'idterm.py'

As shown above, if the file cannot be found by the interpreter or if it cannot be read as a text file, an exception will be raised. Modify function fileLength() so that a friendly message is printed instead:

>>> fileLength('midterm.py')
358
>>> fileLength('idterm.py')
File idterm.py not found.

Explanation / Answer

Code:

def fileLength( fileName):
try:
file = open(fileName)
# Seek to the end. (0 bytes relative to the end)
file.seek(0, 2)
length = file.tell()
return length
except IOError as e:
return 'File '+fileName+' not found.'
print fileLength('hello.txt')
print fileLength('Hai.txt')

hello.txt:

hai hello
how are you
good evening

Output:

34

File Hai.txt not found.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote