-1

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)
  • 2
    `f.seek(0)` should be enough. – bereal Dec 15 '20 at 15:03
  • @bereal provided code to get the file position back to the beginning before starting to read. – Tarik Dec 15 '20 at 15:07
  • Thanks @bereal . Where should I use seek? in all cases I want to follow the methods given by a first course in python and seek does not figure there. – Aymane Fihadi Dec 15 '20 at 15:08
  • 1
    Your options are `seek`, re-open, or read the file to a variable/list and read that how many times you need... – Tomerikoo Dec 15 '20 at 15:09
  • @AymaneFihadi the question linked as a duplicate has the explanation. Call it every time you need to start reading the file over. You can check the [file object documentation](https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects). – bereal Dec 15 '20 at 15:10

1 Answers1

1

You don't need to reopen the file.

def word_count(file_path):
    count_chars=0
    count_words=0
    count_lines=0
    with open(file_path) as f:
        for line in f:
            count_chars += len(line)
            count_words += len(line.split())
            count_lines +=1  
    return (count_chars, count_words, count_lines)

Note that I changed the variable names to one I think are more appropriate.

Roy Cohen
  • 1,540
  • 1
  • 5
  • 22