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('舊文件','新文件')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM