Dec-09-2020, 03:32 AM
Actually, I'm only trying to use the Python wc module to count words in a text file.
wc('/proc/cpuinfo') works nicely in Idle!
But I found this and I am trying to understand it!
I got this from https://code-maven.com/python-wc
It is about using wc (not the toilet
)
We have the function:
I made the above code, both parts, into a function, myApp() If I run myApp() in Idle I get:
My path is:
path = '/home/pedro/winter2020/20PY/dumpFiles/'
I thought, if I just pass it a list, the "splat" would open the list and the function would do the job, but I get an error.
>
I got the files:
wc('/proc/cpuinfo') works nicely in Idle!
But I found this and I am trying to understand it!
I got this from https://code-maven.com/python-wc
It is about using wc (not the toilet

We have the function:
def wc(*filenames): results = {} for filename in filenames: chars = 0 words = 0 lines = 0 try: with open(filename) as fh: for line in fh: lines += 1 words += len(line.split()) chars += len(line) results[filename] = { 'lines': lines, 'words': words, 'chars': chars, } except Exception as err: print(err) return resultsThen the main part, which I can't follow. Can you please explain it to me??
if __name__ == '__main__': import sys if len(sys.argv) < 1: exit("Usage: {} FILENAMEs".format(sys.argv[0])) results = wc(*sys.argv[1:]) totals = { 'lines': 0, 'words': 0, 'chars': 0, } for filename in results: res = results[filename] print("{} {} {} {}".format(res['lines'], res['words'], res['chars'], filename)) for k in res: totals[k] += res[k] print("{} {} {} {}".format(totals['lines'], totals['words'], totals['chars'], 'total'))How this main part supposed to know where the files are? Which files?
I made the above code, both parts, into a function, myApp() If I run myApp() in Idle I get:
Quote:>>> myApp()
0 0 0 total
>>>
My path is:
path = '/home/pedro/winter2020/20PY/dumpFiles/'
I thought, if I just pass it a list, the "splat" would open the list and the function would do the job, but I get an error.
>
Quote:>> myresults = wc(pathtoFiles)
expected str, bytes or os.PathLike object, not list
I got the files:
files = os.listdir(path)Then ran this to get a list of path + file:
for file in files: getFile = os.path.join(path, file) if os.path.isdir(getFile): # this checks if file is a folder continue # don't get folders, use continue else: pathtoFiles.append(getFile)I have a nice list of path + filename, but the function wc() above doesn't like this. Why is that?