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.
Yes, it is possible.
– Maniero