从python中的文件夹读取多个.txt文件的名称

时间:2019-03-04 02:59:12

标签: python regex

是否可以从单个文件夹中读取多个.txt文件的名称?我现在只能读取文件的内容。

import glob
import errno
path = 'C:/Users/rabhi/Desktop/NLP/aclImdb/test/neg/*.txt'
files = glob.glob(path)
for name in files:
    try:
        with open(name) as f:
            for line in f:
                print(line.split())
    except IOError as exc: 
        if exc.errno != errno.EISDIR:
            raise 

1 个答案:

答案 0 :(得分:0)

您可以为此使用os.walk()

import os
def main():
    for dirName, subDirList, fileList in os.walk('path'):
        for subDir in subDirList:
            for file in fileList:
                #Do something with file
main()

这将递归遍历给定目录中的文件。 要忽略子目录,您可以尝试以下操作:

import os
def main():
    for dirName, subDirList, fileList in os.walk('path'):
        for file in fileList:
            #Do something with file
main()