I have been asked to create a function that returns the total number of characters in a file (including newline characters) whose name is given as a parameter. My code seems to work fine for single line files, but it won't total the characters in a multi-line file.
def file_size(filename):
"""returns a count of the number of characters in the file
whose name is given as a parameter."""
filename = open(filename)
lines = filename.readlines()
for line in lines:
length = len(line[::-1])
return length
filename.close()
The Python documentation states (emphasis mine):
To read a file’s contents, call
f.read(size)
, which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode).size
is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory.
So, we can do the following:
.read()
without a size
parameterlen()
on the result of the call to .read()
:len(filename.read())
That being said, to fix your immediate issue, you have an indentation error; you return after the first iteration of the for
loop. This:
for line in lines:
length = len(line[::-1])
return length
should be:
for line in lines:
length = len(line[::-1])
return length
so that you only return once all the lines have been processed.