python实现对文件夹内所有jpg图片的提取 |
您所在的位置:网站首页 › 从多个文件夹提取文件夹到一个文件夹python › 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│ └── 蓝色气泡│ ├── [email protected]│ ├── [email protected]│ ├── [email protected]│ ├── [email protected]│ ├── [email protected]│ ├── [email protected]│ ├── [email protected]│ ├── [email protected]│ ├── [email protected]│ └── Thumbs.db├── test1│ ├── nobody.txt│ ├── test1.c│ └── test2.c└── test24 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:['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '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:]:.rbshutil模块,高级的文件,文件夹,压缩包处理模块。 shutil.move('旧文件','新文件') |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |