读取所有目录中的所有文件

Rel*_*ve0 9 python directory-structure file file-handling

我有代码工作来读取单个文本文件的值,但是很难从所有目录中读取所有文件并将所有内容放在一起.

这是我有的:

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
Run Code Online (Sandbox Code Playgroud)

请注意,我正在尝试将通配符*插入文件名以及文件后缀的通配符.我收到以下错误:

"IOError:[Errno 2]没有这样的文件或目录:'Test/. '"

我不确定这是否是正确的方法,但似乎如果我以某种方式让通配符工作 - 它应该工作.

我已经得到了这个例子: Python - 从子目录中找不到目录文件中的文件(在那里)

这有点不同 - 但不知道如何更新它来读取所有文件.我在想这个初始代码集:

previous_dir = os.getcwd()
os.chdir('testfilefolder')
#add something here?
for filename in os.listdir('.'):
Run Code Online (Sandbox Code Playgroud)

我需要添加一些东西,我有一个外部for循环,但不知道该放入什么..

有什么想法吗?

Mar*_*ers 17

Python不直接在open()调用的文件名中支持通配符.您需要使用该glob模块来从单个子目录级别加载文件,或者用于os.walk()遍历任意目录结构.

打开所有子目录中的所有文本文件,深度为一级:

import glob

for filename in glob.iglob(os.path.join('Test', '*', '*.txt')):
    with open(filename) as f:
        # one file open, handle it, next loop will present you with a new file.
Run Code Online (Sandbox Code Playgroud)

打开任意目录嵌套中的所有文本文件:

import os
import fnmatch

for dirpath, dirs, files in os.walk('Test'):
    for filename in fnmatch.filter(files, '*.txt'):
        with open(os.path.join(dirpath, filename)):
            # one file open, handle it, next loop will present you with a new file.
Run Code Online (Sandbox Code Playgroud)