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.