As Isdeev pointed out, listdir () returns only file names, not the full path (or relative paths). Another way to solve this problem is os.chdir() to the directory in question, then os.listdir('.') .
Secondly, it seems your goal is to count the frequency of words, not letters (characters). To do this, you need to break the contents of the files into words. I prefer to use regular expression for this.
Thirdly, your decision takes into account the frequency of words for each file separately. If you need to do this for all files, first create a Counter() object, then call the update() method to count the counts.
Without further ado, my solution:
import collections import re import os all_files_frequency = collections.Counter() previous_dir = os.getcwd() os.chdir('testfilefolder') for filename in os.listdir('.'): with open(filename) as f: file_contents = f.read().lower() words = re.findall(r"[a-zA-Z0-9']+", file_contents)
Hai vu
source share