This should be basic but I can't find a quick response to my question, sorry if this is a double.
I am writing a small code to learn how to manipulate files and count the number of lines, words and of character inside a txt file.
Could you please explain why in the code below if I don't reload for the second time the file using another with open()
, the code fails to count the len(f.read)
properly? Without it, it returns 0.
Comments to improve the code are welcomed.
def wc(nomFichier):
nb_car=0
nb_words=0
nb_lig=0
with open(nomFichier) as f:
for line in f:
words = line.split()
nb_words += len(words)
nb_lig +=1
with open(nomFichier) as f: #Why I need to reload the file?
nb_car=len(f.read()) #f.read().stripignore to ignore ligne\n
f.close()
return (nb_car, nb_words, nb_lig)