python合并不同文件夹下所有文件

来源:互联网 发布:sql语句中的关键字 编辑:程序博客网 时间:2024/05/22 16:58

工作中有时候会遇到需要将不同文件夹下的所有细小的文件合并起来,python中有很好的遍历文件的函数和拷贝文件函数

os模块walk函数

for roots, dirs, files in os.walk(path):

roots :当前遍历的根目录

dirs :当前遍历根目录下的所有目录

files :当前遍历根目录下的所有文件,存储在列表

shutil模块

copyfileobj(srcfileobj, dstfileobj), 参数为打开文件的对象

copyfile(srcfile, dstfile), 参数为文件本身

注意:目标文件不能在要处理的目录下面,不然的话目标文件也会遍历读取一次

代码如下:

#-*- coding: utf-8 -*-import osimport shutilpath = "/root/tmp/a"target = "/root/tmp/result.txt"print targetappendfile = open(target, 'a+')for roots, dirs, files in os.walk(path):    for ifile in files:        tempfile = roots + '/' + ifile        openfile = open(tempfile)        print tempfile        shutil.copyfileobj(openfile, appendfile)        openfile.close()appendfile.close()


 

0 0
原创粉丝点击