Create a function that returns information about a file

Asked

Viewed 125 times

0

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

The information we have to show is: # line, # of words and # character.

I am asking this because I would like to be sure, since one of the teachers complained about some things he had not done, for example the fact that he had not controlled 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 whether it is possible, in general, to improve this simple function.

  • 5

    Yes, it is possible.

1 answer

0

It’s a little too big this code. I’d 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.