繁体   English   中英

将同一目录中具有相同扩展名的文件复制到另一个目录 - Python

[英]Copy files with same extensions in the same directory to another directory - Python

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

我有一些伪代码如下:

import os, shutil

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

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

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

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")

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

您可以使用 os 中的listdir并从shutil 中复制

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 ,我不好。

我终于通过所有回复的组合得到了自己的正确答案。

因此,如果我在 (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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM