我有代码可以读取单个文本文件的值,但在读取所有目录中的所有文件并将所有内容放在一起时遇到困难。
这是我所拥有的:
filename = '*'
filesuffix = '*'
location = os.path.join('Test', filename + "." + filesuffix)
Document = filename
thedictionary = {}
with open(location) as f:
file_contents = f.read().lower().split(' ') # split line on spaces to make a list
for position, item in enumerate(file_contents):
if item in thedictionary:
thedictionary[item].append(position)
else:
thedictionary[item] = [position]
wordlist = (thedictionary, Document)
#print wordlist
#print thedictionary
请注意,我试图将通配符 * 粘贴到文件名以及文件后缀的通配符中。我收到以下错误:
“IOError:[Errno 2]没有这样的文件或目录:'测试/.'"
我不确定这是否是正确的方法,但似乎如果我以某种方式使通配符起作用 - 它应该起作用。
我已经让这个例子工作了:Python - 从子目录(在那里)中找不到的目录文件中读取文件 https://stackoverflow.com/questions/15580716/python-reading-files-from-directory-file-not-found-in-subdirectory-which-is-t
这有点不同 - 但不知道如何更新它以读取所有文件。我认为在这组初始代码中:
previous_dir = os.getcwd()
os.chdir('testfilefolder')
#add something here?
for filename in os.listdir('.'):
我需要添加一些东西,我有一个外部 for 循环,但不太知道要放什么。
有什么想法吗?