python实现对文件夹内所有jpg图片的提取

之前下载了一个壁纸合集,但是子文件夹太多,看图片的时候体验贼鸡儿差。所以想把所有的图片提取到一个文件夹内,在网上搜了一下感觉大部分博客内容大同小异,都是直接给出了代码。由于本人小白一只,难免出错,以下是具体代码和解释。

import os
import shutil
path = '要提取的文件夹i地址'
new_path = '新文件地址'

for root,dirs,files in os.walk(path):
    for i in range(len(files)):
        if(files[i][-3:] == 'jpg'):
            file_path = root + '/' + files[i]
            new_file_path = new_path + '/' + files[i]
            shutil.mov(file_path,new_file_path)

os模块,即系统模块。主要用于处理文件和目录,其最大的特点是可以跨平台。

os.walk()方法就是在目录中游走输出,语法格式为:

os.wlak(top[,topdown = True[,onerror = None[,followlinks = False]]])

总共有四个参数:

1)top,产生三元组:文件夹路径,文件夹名字,文件名。

2)topdown,True则自上而下,False则自下而上。

3)onerror,是一个函数,调用一个参数,出现错误时继续wlak或者抛出异常停止walk。

4)followlinks,true时可以通过软链接访问目录。

举个栗子:

.
├── fikwe.rb
├── jfsdi.py
├── test
│   └── 蓝色气泡
│       ├── chat_recive_nor@2x.png
│       ├── chat_recive_nor_pic@2x.png
│       ├── chat_recive_press@2x.png
│       ├── chat_recive_press_pic@2x.png
│       ├── chat_send_dim@2x.png
│       ├── chat_send_nor@2x.png
│       ├── chat_send_nor_pic@2x.png
│       ├── chat_send_press@2x.png
│       ├── chat_send_press_pic@2x.png
│       └── Thumbs.db
├── test1
│   ├── nobody.txt
│   ├── test1.c
│   └── test2.c
└── test2

4 directories, 15 file

 测试代码为:

import os
for root,dirs,files in os.walk('/root/test',True):
    print 'root:%s' %root
    print 'dirs:%s' %dirs
    print 'files:%s' %files
    print

输出结果为:

root:/root/test
dirs:['test', 'test2', 'test1']
files:['jfsdi.py', 'fikwe.rb']

root:/root/test/test
dirs:['\xe8\x93\x9d\xe8\x89\xb2\xe6\xb0\x94\xe6\xb3\xa1']
files:[]

root:/root/test/test/蓝色气泡
dirs:[]
files:['chat_send_press_pic@2x.png', 'chat_send_nor_pic@2x.png', 'chat_recive_press_pic@2x.png', 'chat_send_dim@2x.png', 'chat_recive_nor@2x.png', 'chat_send_nor@2x.png', 'chat_recive_nor_pic@2x.png', 'chat_recive_press@2x.png', 'chat_send_press@2x.png', 'Thumbs.db']

root:/root/test/test2
dirs:[]
files:[]

root:/root/test/test1
dirs:[]
files:['test1.c', 'test2.c', 'nobody.txt']

root为/root/test/test的dirs因为汉字所以显示的乱码。

files[i]直接输出全部的文件名,而files[i][-3:]输出的是该文件的扩展名。

import os
for root,dirs,files in os.walk('/root/test',True):
    for i in range(len(files)):
        print 'files[%s]:' %i + files[i]
        print 'files[%s][-3:]:'%i +files[i][-3:]
    print 

输出结果:

files[0]:jfsdi.py
files[0][-3:]:.py
files[1]:fikwe.rb
files[1][-3:]:.rb

shutil模块,高级的文件,文件夹,压缩包处理模块。

shutil.move('旧文件','新文件')

posted @ 2018-03-29 11:23  三寸碧玉心  阅读(9749)  评论(0编辑  收藏  举报