2017-08-31 71 views
1

我需要獲取不同文件夾中最大尺寸的文件,將它們的名稱更改爲它們所屬的文件夾名稱並保存到一個新的文件夾。我有這樣的事情,我卡住了:如何獲取文件夾中最大尺寸的文件,更改其名稱並保存到其他文件夾

import os 

# Core settings 
rootdir = 'C:\\Users\\X\\Desktop\\humps' 
to_save = 'C:\\Users\\X\\Desktop\\new' 

for root, dirs, files in os.walk(rootdir): 
     new_list = [] 
     for file in files: 
      if file.endswith(".jpg"): 
       try: 
        print(file) 
        os.chdir(to_save) 
        add_id = root.split("humps\\")[1] 
        add_id = add_id.split("\\")[0] 
        file_name = os.path.join(root,file) 
        new_list.append(file_name) 
        bigfile = max(new_list, key=lambda x: x.stat().st_size) 


       except: 
        pass 

爲了更清楚:比方說,子文件夾的名稱是「大象」,並有不同的大象照片和子文件夾在這頭大象的文件夾。我想通過這些照片和子文件夾,找到最大尺寸的大象照片,將其命名爲大象並將其保存到我的目標文件夾中。還爲其他子文件夾,如獅子,美洲獅等重新調整它。 我怎麼能達到我想要的?

+0

因此,讓我們假設有不同的文件夾,每個文件夾都有很多文件。對於那些文件夾,我想以kbs的方式獲得最大尺寸的文件 – edyvedy13

+0

如果文件夾中有多個文件的最大尺寸,您想要做什麼?您是否需要掃描rootdir文件夾中的JPEG文件,或者是否需要在這些文件夾內還需要搜索JPEG文件夾? –

+0

的確,可能有一些子文件夾。爲了更清楚:假設文件夾的名稱是「大象」,在這個大象文件夾中有不同的大象照片和子文件夾。我想通過這些照片和子文件夾,並找到大象最大的照片,將其命名爲大象並將其保存到我的目標文件夾 – edyvedy13

回答

1

How to get the files with the biggest size in the folders, change their name and save to a different folder

基本上你已經擁有的,你需要做的一個很好的說明。你只需要按照它一步一步:

  1. 得到的所有文件在一些搜索目錄
  2. 對相關的文件過濾器(「* .JPG」)
  3. 得到它們的大小
  4. 找到最大
  5. 複製到新目錄與搜索目錄

的名稱國際海事組織這是一個重要的技能,能夠將任務分解成更小的任務。然後,你只需要實現更小的任務,並結合:


def iterate_files_recursively(directory="."): 
    for entry in os.scandir(directory): 
    if entry.is_dir(): 
     for file in iterate_files_recursively(entry.path): 
     yield file 
    else: 
     yield entry 

files = iterate_files_recursively(subfolder_name) 

我會使用os.scandir,因爲它避免了建立在內存中的文件(潛在的)巨大的名單,而是讓我(通過發生器)一次處理一個文件。請注意,從3.6開始,可以使用os.scandir的結果作爲上下文管理器(with語法)。

images = itertools.filterfalse(lambda f: not f.path.endswith('.jpg'), files) 

過濾是除的ìtertools.filterfalse國際海事組織奇怪的選擇,只保留針對其謂語返回False元素相對簡單。

biggest = max(images, key=(lambda img: img.stat().st_size)) 

這是一個兩個步驟:獲取與內置max函數的最大值,並使用該文件大小的「鑰匙」,以建立一個訂單。請注意,如果您沒有任何圖像,則會產生ValueError ...所以您可能需要提供default=None或處理該異常。

shutil.copy(biggest.path, os.path.join(target_directory, subfolder_name + '.jpg') 

shutil.copy複製文件和一些元數據。而不是硬編碼路徑分隔符,請使用os.path.join

現在所有這些都假設您知道subfolder_name。您也可以輕鬆地掃描那些:

def iterate_directories(directory='.'): 
    for entry in os.scandir(directory): 
    if entry.is_dir(): 
     yield entry 
+0

非常感謝你真棒的答案 – edyvedy13

1

這裏有一些代碼可以做你想做的。它不使用舊的os.walk函數,而是使用現代的pathlib函數。

此代碼的核心是遞歸biggest函數。它會掃描folder中的所有文件和目錄,將匹配的文件名保存到files列表中,並遞歸搜索它找到的任何目錄。然後它返回找到的最大文件的路徑,如果找不到匹配的文件,則返回None

from pathlib import Path 
import shutil 

def filesize(path): 
    return path.stat().st_size 

def biggest(folder, pattern): 
    ''' Find the biggest file in folder that matches pattern 
     Search recursively in all subdirectories 
    ''' 
    files = [] 
    for f in folder.iterdir(): 
     if f.is_file(): 
      if f.match(pattern): 
       files.append(f) 
     elif f.is_dir(): 
      found = biggest(f, pattern) 
      if found: 
       files.append(found) 
    if files: 
     return max(files, key=filesize) 

def copy_biggest(src, dest, pattern): 
    ''' Find the biggest file in each folder in src that matches pattern 
     and copy it to dest, using the folder's name as the new file name 
    ''' 
    for path in src.iterdir(): 
     if path.is_dir(): 
      found = biggest(path, pattern) 
      if found: 
       newname = dest/path 
       print(path, ':', found, '->', newname) 
       shutil.copyfile(found, newname) 

你可以這樣調用:

rootdir = r'C:\Users\X\Desktop\humps' 
to_save = r'C:\Users\X\Desktop\new' 
copy_biggest(Path(rootdir), Path(to_save), '*.jpg') 

注意,複製的文件將具有相同的名稱,他們發現在rootdir頂層文件夾,沒有文件擴展名。如果你想給他們一個.jpg擴展,你可以改變

newname = dest/path 

newname = (dest/path).with_suffix('.jpg') 

shutil模塊上的舊版本的Python 3的不理解pathlib路徑。但這很容易解決。在copy_biggest功能,更換

shutil.copyfile(found, newname) 

shutil.copyfile(str(found), str(newname)) 
+0

它引發:TypeError:參數應該是字符串,字節或整數,而不是WindowsPath – edyvedy13

+0

@ edyvedy13對不起。它在Python 3.6上運行良好。但修復起來很容易,因此它可以在Python 3.4或3.5上運行。我會編輯我的答案。 –

2

要找到最大的文件並保存到另一個位置

import os 
import shutil 

f_list = [] 

root = "path/to/directory" 
root = os.path.abspath(root) 

for folder, subfolders, files in os.walk(root): 
    for file in files: 

     filePath = os.path.join(folder, file) 
     f_list.append(filePath) 


bigest_file = max(f_list,key=os.path.getsize) 
new_path = "path/where/you/want/to/save" 
shutil.copy(biggest_file,new_path) 

,如果你只想要的圖像,然後在循環

增加一個條件
for folder, subfolders, files in os.walk(root): 
    for file in files: 
     if file.endswith(".jpg"): 
      filePath = os.path.join(folder, file) 
      f_list.append(filePath) 

要獲得所有文件夾的最大文件

root = "demo" 
root = os.path.abspath(root) 

def test(path): 
    big_files = [] 
    all_paths = [x[0] for x in os.walk(path)] 

    for paths in all_paths: 

     f_list = filter(os.path.isfile, os.listdir(paths)) 
     if len(f_list) > 0: 
      big_files.append((paths,max(f_list,key=os.path.getsize))) 
    return big_files 


print test(root) 
+0

它引發此錯誤:NameError:名稱'img'未定義 – edyvedy13

+0

@ edyvedy13我更新我的答案,請檢查它 – Kallz

+0

我應該將bigest_file放入循環中? ValueError:max()arg是一個空序列 – edyvedy13

相關問題