将同一目录中具有相同扩展名的文件复制到另一个目录—Python
我在同一目录中有一些文件具有相同的扩展名(.html)。这些文件都需要复制到另一个目录。我查阅了将同一目录中具有相同扩展名的文件复制到另一个目录—Python,python,directory,copy,Python,Directory,Copy,我在同一目录中有一些文件具有相同的扩展名(.html)。这些文件都需要复制到另一个目录。我查阅了shutil和os上的文档,但找不到任何正确的答案 我有一些伪代码,如下所示: import os, shutil copy file1, file2, file3 in C:\abc to C:\def 如果有人知道如何解决这个问题,请告诉我。谢谢 不久前,我创建了这个脚本,用于对文件夹中的文件进行排序。试试看 import glob import os #get list of file
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")
[假设python3,但应与2.7中的类似] 您可以从操作系统和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)
您应该使用os.join.path而不是“+”。我使用修改过的路径运行此代码,但它返回
AttributeError:module'os'没有属性“splitext”
?我使用Python3.6,我很确定它有splitext