0

Working on a function for input of an arbitrary number of text files as args. Function is to count lines, words and chars for each of the files, as well as a total count:

lines = words = chars = 0

def cfunc(folder, *arg):
    global lines, words, chars

    for x in arg:
        with open("{}{}".format(folder, x), "r") as inp:
            for line in inp:
                lines += 1
                words += len(line.split(" "))
                chars += len(line)
        print(x, lines, words, chars)

cfunc("C:/", "text1.txt", "text2.txt", "text3.txt")

The counter is correct for the first file. For the third the counter essentially shows the total number for lines/words/chars across all 3 files. As i understand, this happens because inp reads all 3 files together and the counter is the same across all files. How could i separate the counters to print statistics for each file individually?

2
  • 4
    Why are you using a global?! That's explicitly exactly the opposite of the behaviour you say you want. If you put lines = words = chars = 0 inside the loop, you'll get the count for each file separately. Commented Oct 1, 2015 at 13:27
  • why are you using global here? Commented Oct 1, 2015 at 13:27

1 Answer 1

1

First, you need to reset your statistics for each file:

for x in arg:
    lines = words = chars = 0
    with open("{}{}".format(folder, x), "r") as inp:
        ...

Second, to keep a total count you need to use separate variables since you're now resetting the variables for each iteration:

total_lines = total_words = total_characters = 0

def cfunc(folder, *arg):
    global total_lines, total_words, total_chars

    for x in arg:
        ...
        print(x, lines, words, chars)
        total_lines += lines
        total_words += words
        total_chars += chars

Of course you can name your global variables lines, words, and chars if you want, you then just have to use different names for the variables you use inside the loop.

Sign up to request clarification or add additional context in comments.

1 Comment

A, i felt that i was close, damn! :)) The individual counter just needed to be inside the loop, with the global one outside. Great answer! Thank you 👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.