python复制与删除文件夹的小例子

发布时间:2019-09-05编辑:脚本学堂
本文介绍二个python的小例子,分别实现文件夹的复制与删除,学习下python中os模块的用法,挺不错的,有需要的朋友不妨作个参考。

本节内容:
python os模块实现文件夹的复制与删除。

例1,python复制文件夹。
 

复制代码 代码示例:

#!/bin/python
#
#site: www.jb200.com
def CopyFolderOs(sFolder,tFolder):
    sourcePath = sFolder
    destPath = tFolder
    for root, dirs, files in os.walk(sourcePath):

        #figure out where we're going
        dest = destPath + root.replace(sourcePath, '')

        #if we're in a directory that doesn't exist in the destination folder
        #then create a new folder
        if not os.path.isdir(dest):
            os.mkdir(dest)
            print 'Directory created at: ' + dest

        #loop through all files in the directory
        for f in files:
            #compute current (old) & new file locations
            oldLoc = root + '' + f
            newLoc = dest + '' + f

            if not os.path.isfile(newLoc):
                try:
                    shutil.copy2(oldLoc, newLoc)
                    print 'File ' + f + ' copied.'
                except IOError:
                    print 'file "' + f + '" already exists'

例2,python删除文件夹:
 

复制代码 代码示例:
#!/usr/bin/env python 
#
#site: www.jb200.com
def RemoveFolderOs(sourceDir,localAppDataPath):
    for root, dirs, files in os.walk(sourceDir):
        for f in files:
            os.unlink(os.path.join(root, f))
        for d in dirs:
            shutil.rmtree(os.path.join(root, d))

您可能感兴趣的文章:
python实例之复制目录下的文件
python复制文件夹的典型例子
Python os.path和shutil模块实现文件复制与删除
python shutil模块实现文件夹复制的加强版
使用python进行文件复制
python实现文件递归复制的代码
python实现文件复制与删除