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?
global?! That's explicitly exactly the opposite of the behaviour you say you want. If you putlines = words = chars = 0inside the loop, you'll get the count for each file separately.