[英]Copy files with same extensions in the same directory to another directory - Python
我在同一个目录中有一些文件具有相同的扩展名(.html)。 这些文件都需要复制到另一个目录。 我shutil
过关于shutil
和os
文档,但找不到任何正确的答案......
我有一些伪代码如下:
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")
我终于通过所有回复的组合得到了自己的正确答案。
因此,如果我在 (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.