如何将多个图像从一个文件夹移动到python中的另一个文件夹?

时间:2019-10-19 17:07:20

标签: python

我正在尝试使用composeView.attachInlineFiles([file]); 将多个图像从一个文件夹移动到另一个文件夹,我已将图像名称保存在CSV文件中。 例如:shutil.move()

我尝试了以下代码

[img1 , img25, img55....]

TypeError:“ in”要求将字符串作为左操作数,而不是int

2 个答案:

答案 0 :(得分:0)

这里有几个问题,首先,您正在遍历一个数据框,该数据框将返回列标签而不是值-这就是导致您发布错误的原因。如果您确实只想使用熊猫来导入CSV,则可以将其更改为for i in df.iterrows(),但是即使那样,它也不会简单地返回文件名,而是会返回一系列对象。使用标准的CSV模块读取CSV可能会更好。这样,您的文件名将作为列表读入,并且将按您预期的方式运行。

第二,除非代码中发生其他事情,否则您无法使用'in'关键字在文件夹中查找文件,您将需要通过将文件名和文件夹路径串联来构建完整的文件路径。 / p>

答案 1 :(得分:0)

尝试这种方法:

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')