python批量移动文件夹中的文件到新的文件夹

  • 1
  • 13,137 views
  • A+
所属分类:Python学习

最近下载了一波大前端的视频教程,因视频分布到N多个文件夹中,查阅起来就比较麻烦,所以就在想如果这些视频文件全部能搞到一个目录下不是更好吗?

说干就干

 

必备条件

python3 环境

os 模块

shutil 模块

 

代码逻辑

  1. 通过访问指定文件夹
  2. 循环找出符合条件的文件名
  3. 移动文件至新的文件夹

 

代码实现

  1. import os
  2. import shutil
  3. # 旧地址、新地址、文件格式
  4. def filemove(oldfile, newfile, fileformat):
  5.     # 列出文件下所有文件
  6.     weblist = os.walk(oldfile)
  7.     newpath = newfile
  8.     for path, d, filelist in weblist:
  9.         for filename in filelist:
  10.             if fileformat in filename:
  11.                 full_path = os.path.join(path, filename)  # 旧地址 + 文件名
  12.                 despath = newpath + filename  # 新地址 +文件名
  13.                 print(shutil.move(full_path, despath), '文件移动成功')  # 移动文件至新的文件夹
  14.             else:
  15.                 print('文件不存在', filename)
  16. filemove('/Users/lijinlong/Desktop/大前端/WEB大前端课程/资深', '/Users/lijinlong/Desktop/大前端/WEB大前端课程/资深/', '.mp4')

 

代码升级

增加对两个目录的地址进行判断,后面又想着对文件名称进行判断,发现没什么意义,毕竟程序不是用在入侵上面。

  1. import os
  2. import shutil
  3. # 旧地址、新地址、文件格式
  4. def filemove(oldfile, newfile, fileformat):
  5.     # 列出文件下所有文件
  6.     weblist = os.walk(oldfile)
  7.     # 对上述的两个目录地址进行判断,如不存在则返回不存在信息
  8.     if os.path.exists(newfile) == True and os.path.exists(oldfile) == True:
  9.         newpath = newfile
  10.         for path, d, filelist in weblist:
  11.             for filename in filelist:
  12.                 if fileformat in filename:
  13.                     full_path = os.path.join(path, filename)  # 旧地址 + 文件名
  14.                     despath = newpath + filename  # 新地址 +文件名
  15.                     print(shutil.move(full_path, despath), '文件移动成功')  # 移动文件至新的文件夹
  16.                 else:
  17.                     print('文件不存在', filename)
  18.     else:
  19.         print("目录不存在")
  20. filemove('/Users/lijinlong/Desktop/大前端/WEB大前端课程/资深', '/Users/lijinlong/Desktop/大前端/WEB大前端课程/资深/', '.mp4')

 

最后给自己的乡村做个广告,瓦滩村(www.watancun.com)入选为江苏最美乡村,未来将于华西村肩并肩的乡村,然后这个网站是我做的,年底回家制作内容,互联网能搜索到的内容就这么多了。

 

李金龙

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

目前评论:1   其中:访客  1   博主  0

    • avatar 何三 0

      感谢博主分享 python批量移动文件夹中的文件到新的文件夹,学习了