Matthew Weekly
Matthew Weekly

Reputation: 1

Counting characters in a file in Python

I am trying to write a function that counts the number of characters in a text file and returns the result. I have the following code;

def file_size(filename):
    """Function that counts the number of characters in a file"""
    filename = "data.txt"
    with open(filename, 'r') as file:
        text = file.read()
        len_chars = sum(len(word) for word in text)
        return len_chars

This seemed to be working fine in my IDE when I test ran it with a text file that I created. However when I submit the code to a doctest program I get an error saying it always gives the output of 10. Any help?

Attached is a screenshot of the error message Error screen.

Upvotes: 0

Views: 323

Answers (4)

Chris_Rands
Chris_Rands

Reputation: 41228

You could use sum() with a generator expression around iter(partial(f.read, 1), ''), taking inspiration from this answer:

from functools import partial

def num_chars(filename):
    """Function that counts the number of characters in a file"""
    with open(filename) as f:
        return sum(1 for _ in iter(partial(f.read, 1), ''))

The main advantage of this is approach compared to using f.read() is that it is lazy, so you don't read the whole file into memory.

Upvotes: 0

Sam Chats
Sam Chats

Reputation: 2311

Super efficient solution for ASCII files (runs in theta(1)):

import os
print(os.stat(filename).st_size)

Upvotes: 1

Eric Duminil
Eric Duminil

Reputation: 54303

If you just want the file size of an ASCII file, you should use os.stat :

import os

def file_size(filename):
    st = os.stat(filename)
    return st.st_size

The big advantage with this function is that there's not need to read the file. Python simply asks the filesystem for the file size.

Upvotes: 0

Daniel
Daniel

Reputation: 42778

You don't use the argument of the function but overwrite filename with the constant "data.txt":

def file_size(filename):
    """Function that counts the number of characters in a file"""
    with open(filename, 'r') as file:
        return len(file.read())

Upvotes: 4

Related Questions