【问题标题】:Reading all files in all directories [duplicate]读取所有目录中的所有文件[重复]
【发布时间】:2013-04-07 14:42:58
【问题描述】:

我的代码可以读取单个文本文件的值,但在读取所有目录中的所有文件并将所有内容放在一起时遇到困难。

这是我所拥有的:

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] 没有这样的文件或目录:'Test/.'"

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

我已经让这个例子工作了:Python - reading files from directory file not found in subdirectory (which is there)

这有点不同 - 但不知道如何更新它以读取所有文件。我在想,在这组初始代码中:

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

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

有什么想法吗?

【问题讨论】:

    标签: python file file-handling directory-structure


    【解决方案1】:

    Python 不支持在 open() 调用的文件名中直接使用通配符。您需要使用 glob module 来从单级子目录加载文件,或使用 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.
    

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

    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.
    

    【讨论】:

    • 感谢 Martijn。我会尝试一下,看看会发生什么。我很好奇为什么他们要制作两个不同的函数 glob 和 os.walk。稍微阅读一下,我确实看到 glob 将允许您使用通配符,但 os.walk 不会 - 相反,您需要过滤结果。我不明白到底发生了什么,因为当我考虑过滤我认为通配符表达式所做的结果时。我发现了这篇文章:stackoverflow.com/questions/8931099/quicker-to-os-walk-or-glob 如果您有任何见解和时间,任何想法都将不胜感激。
    • glob() 不支持任意嵌套子目录(目前)。这是这里唯一的区别。 os.walk() 可以,但需要更多过滤。请注意,glob() 在它自己的实现中已经使用了相同的过滤方法fnmatch 模块)。
    猜你喜欢
    • 2013-12-02
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多