【发布时间】:2018-03-13 14:11:02
【问题描述】:
我在同一目录中有一些具有相同扩展名(.html)的文件。这些文件都需要复制到另一个目录。我查看了shutil 和os 的文档,但找不到任何正确的答案...
我有一些伪代码如下:
import os, shutil
copy file1, file2, file3 in C:\abc
to C:\def
如果有人知道如何解决这个问题,请告诉我。赞赏!!
【问题讨论】:
我在同一目录中有一些具有相同扩展名(.html)的文件。这些文件都需要复制到另一个目录。我查看了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")
【讨论】:
【讨论】:
AttributeError: module 'os' has no attribute 'splitext'?我使用 python 3.6,我很确定它有 splitext
综合所有回复,我自己终于得到了正确答案。
所以如果我在 (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)
【讨论】: