Home  >  Article  >  Backend Development  >  Python copies files to a specified directory

Python copies files to a specified directory

不言
不言Original
2018-04-27 10:18:174506browse

下面为大家分享一篇python复制文件到指定目录的实例,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

周末出去爬山,照了一大堆照片回来,照片同时存储为jpg和DNG格式,我用adobe bridge将dng格式的照片中要保留的筛选出来后,就不想再对着一张张去挑jpg的照片了,于是用python写个小程序帮我挑,代码如下所示:

import os
import shutil
targetnames = os.listdir('D:\\Pictures\\照片\\2016年\\东灵山\\star')
filenames = os.listdir('D:\\Pictures\\照片\\2016年\\东灵山\\jpg')
flag=[]
for name in targetnames:
 if '.DNG'==name[-4:]:
  targetnames[targetnames.index(name)]=name[:-4]
  flag.append(True)
 else:
  flag.append(False)
  continue
for name in targetnames:
 if flag[targetnames.index(name)]:
  for sname in filenames:
   if '.JPG' ==sname[-4:]:
    if name==sname[:-4]:
     shutil.copyfile('D:\\Pictures\\照片\\2016年\\东灵山\\jpg\\'+sname,'D:\\Pictures\\照片\\2016年\\东灵山\\fabu\\'+sname)

使用了os和shutil两个模块,os.listdir用于读取目标目录中的文件名称,star文件夹中存储了我手动筛选出来的DNG格式图片,jpg文件夹中存储了所有的jpg格式图片,于是在获取到所有DNG格式图片后使用flag数组标记一下,然后循环遍历targetnames数组寻找对应名称的jpg文件,找到的话就使用shutil.copyfile复制到指定文件夹,然后就大功告成了!

相关推荐:

python获取程序执行文件路径的方法

Python3.5 创建文件的简单实例

The above is the detailed content of Python copies files to a specified directory. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn