Python遍历文件夹

来源:互联网 发布:有人买过淘宝店吗 编辑:程序博客网 时间:2024/06/01 09:00

最近做文本聚类要扫描大量的文本,因此,需要遍历文件夹和子文件夹下面的大量文件,记录一下python是如何实现的。


# python遍历文件夹内所有文件,返回文件名即后缀import osfor filename in os.listdir(r'/Users/John/Documents/NLPStudy/tc-corpus-train/C3-Art/'):    print filenameimport glob # 可以设置文件过滤,输出为文件路径for filename in glob.glob('/Users/John/Documents/NLPStudy/tc-corpus-train/C3-Art/*.txt'):    print filenameprint '\n\n\n\n'import os.path # 可以访问子文件夹,只返回文件名及后缀def processDirectory(args, dirname, filenames):    print 'Directory', dirname    for filename in filenames:        print 'File', filenameos.path.walk(r'/Users/John/Documents/NLPStudy/tc-corpus-train/', processDirectory, None)

第三种方法可以遍历子文件夹,减少代码量,第二种方法可以输出全部的文件路径比较方便,自己取舍着用吧,里面的路径改成你自己的路径就可以了。


判断文件与目录是否存在

import osos.path.isfile('test.txt') # 如果不存在返回falseos.path.exists('directory') # 如果目录不存在返回false


0 0
原创粉丝点击