【问题标题】:Copy files with same extensions in the same directory to another directory - Python将同一目录中具有相同扩展名的文件复制到另一个目录 - Python
【发布时间】:2018-03-13 14:11:02
【问题描述】:

我在同一目录中有一些具有相同扩展名(.html)的文件。这些文件都需要复制到另一个目录。我查看了shutilos 的文档,但找不到任何正确的答案...

我有一些伪代码如下:

import os, shutil

copy file1, file2, file3 in C:\abc
to C:\def

如果有人知道如何解决这个问题,请告诉我。赞赏!!

【问题讨论】:

    标签: python directory copy


    【解决方案1】:

    前段时间我创建了这个脚本来对文件夹中的文件进行排序。试试看。

    import glob
    import os
    
    #get list of file 
    orig = glob.glob("G:\\RECOVER\\*")
    
    dest = "G:\\RECOVER_SORTED\\"
    
    count = 0
    
    #recursive function through all the nested folders
    def smista(orig,dest):
        for f in orig:
                #split filename at the last point and take the extension
                if f.rfind('.') == -1:
                    #in this case the file is a folder
                    smista(glob.glob(f+"\\*"),dest)
                else:
                    #get extension
                    ext = f[f.rfind('.')+1:]
    
                    #if the folder does not exist create it
                    if not os.path.isdir(dest+ext):
                        os.makedirs(dest+ext)
                    global count
                    os.rename(f,dest+ext+"\\"+str(count)+"."+ext)
                    count = count+1
    #if the destination path does not exist create it            
    if not os.path.isdir(dest):
                os.makedirs(dest)
    
    smista(orig,dest)
    input("press close to exit")
    

    【讨论】:

    • 你应该使用 os.join.path 而不是 "+"
    【解决方案2】:

    [假设是python3,但在2.7应该类似]

    您可以使用来自 os 的listdir 和来自shutil 的copy

    import os, shutil, os.path
    
    for f in listdir("/path/to/source/dir"):
        if os.path.splitext(f)[1] == "html":
            shutil.copy(f, "/path/to/target/dir")
    

    警告:这是在未经测试的情况下一起报废的。欢迎指正

    编辑(因为我无法评论): @ryan9025 splitext 来自os.path,我的错。

    【讨论】:

    • 我用修改后的路径运行这段代码,但它返回AttributeError: module 'os' has no attribute 'splitext'?我使用 python 3.6,我很确定它有 splitext
    【解决方案3】:

    综合所有回复,我自己终于得到了正确答案。

    所以如果我在 (a) 目录中有一个 python 脚本,所有源文件都在 (b) 目录中,并且目标在 (c) 目录中。

    下面是应该可以工作的正确代码,而且看起来也很整洁。

    import os
    import shutil
    import glob
    
    src = r"C:/abc"
    dest = r"C:/def"
    
    os.chdir(src)
    for files in glob.glob("*.html"):
            shutil.copy(files, dest)
    

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 2015-06-12
      • 2014-06-18
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多