分享

python对文件夹的一些操作

 心不留意外尘 2016-08-02
http://www.oschina.net/code/snippet_72895_1576

 2010

1. [代码]复制文件夹   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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. [代码]删除文件夹     跳至 [1] [2] [全屏预览]

1
2
3
4
5
6
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))

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约