簡體   English   中英

如何將多個圖像從一個文件夾移動到 python 中的另一個文件夾?

[英]how to move multiple images from a folder to another folder in python?

我正在嘗試使用shutil.move()將多個圖像從一個文件夾移動到另一個文件夾,我已將圖像名稱保存在 CSV 文件中。 例如: [img1, img25, img55....]

我試過下面的代碼

import pandas as pd
import shutil

cop_folder = path to folder containing images    
destination_folder = path wher i want to move the images


df = pd.read_csv('', header = None)    
for i in df:       
    if i in cop_folder:
        shutil.move( i, dest_folder)
    else:
        print('fail')

TypeError: 'in' 需要字符串作為左操作數,而不是 int

這里有一些問題,首先您正在迭代 dataframe 它將返回列標簽而不是值 - 這就是導致您發布的錯誤的原因。 如果您真的想使用 pandas 來導入 CSV 那么您可以for i in df.iterrows()但即使這樣它也不會簡單地返回文件名,它會返回一系列 ZA8CFDE6331BD59EB216Z96F966 您最好使用標准 CSV 模塊來讀取 CSV。 這樣,您的文件名將作為列表讀入,並按照您的預期運行。

其次,除非您的代碼中發生了其他事情,否則您無法使用“in”關鍵字在文件夾中查找文件,您需要通過連接文件名和文件夾路徑來構建完整的文件路徑。

試試這個方法:

import pandas as pd
import os


def move_file(old_file_path, new_directory):
    if not os.path.isdir(new_directory):
        os.mkdir(new_directory)
    base_name = os.path.basename(old_file_path)
    new_file_path = os.path.join(new_directory, base_name)
    # Deletes a file if that file already exists there, you can change this behavior
    if os.path.exists(new_file_path):
        os.remove(new_file_path)
    os.rename(old_file_path, new_file_path)


cop_folder = 'origin-folder\\'

destination_folder = 'dest_folder\\'

df = pd.read_csv('files.csv', header=None)

for i in df[0]:
    filename = os.path.join(cop_folder, i)
    move_file(filename, destination_folder)

csv 內的文件名必須有擴展名。 如果他們沒有,那么你應該使用 filename = os.path.join(cop_folder, i + '.jpg')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM