Create a function that returns information about a file

0

I have to create a simple function that writes in the idle information about a file. I have already done many functions of this type, I had even created a notepad in C #, but I wonder if what I am doing is correct and why.

The information we have to show is: # of lines , # of words and # of characters .

I am asking this because I would like to be sure, since one of the professors complained about some things he had not done, for example the fact that he had not checked whether a line was empty or not.

f_name = "text.txt"

import os

def get_file_stats(file_name=""):
    while not os.path.isfile(file_name):
        file_name = input("Enter a valid existing file name: ")

    with open(file_name) as file:
        lines, words, chars = 0, 0, 0

        for line in file: 
            if line:
                lines += 1
                words += len(line.strip().split())

                for c in line: # count the number of chars.
                    if c.isalpha(): # checks if the character is a word character
                        chars += 1

        print("Lines:", lines)
        print("Words:",words)
        print("Chars:",chars)

get_file_stats(f_name)

I would like to know if it is usually possible to improve this simple function.

    
asked by anonymous 09.11.2014 / 18:28

1 answer

1

The code is a little too large. I would do something like this:

fname = "text.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        if len(words) > 0: 
            num_lines += 1
            num_words += len(words)
            for c in line:
                if c.isalpha():
                    num_chars += 1

print("Lines: ", num_lines)
print("Words: ", num_words)
print("Chars: ", num_chars)
    
10.11.2014 / 02:50