[英]how to move multiple images from a folder to another folder in python?
I am trying to move multiple images from one folder to another, using shutil.move()
, I have saved image names in a CSV file.我正在尝试使用
shutil.move()
将多个图像从一个文件夹移动到另一个文件夹,我已将图像名称保存在 CSV 文件中。 ex: [img1, img25, img55....]
例如:
[img1, img25, img55....]
I Have tried the below code我试过下面的代码
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 ' requires string as left operand, not int TypeError: 'in' 需要字符串作为左操作数,而不是 int
There are a few issues here, firstly you are iterating over a dataframe which will return the column labels not the values - that's what's causing the error the you posted.这里有一些问题,首先您正在迭代 dataframe 它将返回列标签而不是值 - 这就是导致您发布的错误的原因。 If you really want to use pandas just to import a CSV then you could change it to
for i in df.iterrows()
but even then it won't simply return the file name, it will return a series object.如果您真的想使用 pandas 来导入 CSV 那么您可以
for i in df.iterrows()
但即使这样它也不会简单地返回文件名,它会返回一系列 ZA8CFDE6331BD59EB216Z96F966 You'd probably be better off using the standard CSV module to read the CSV.您最好使用标准 CSV 模块来读取 CSV。 That way your filenames will be read in as a list and will behave as you intended.
这样,您的文件名将作为列表读入,并按照您的预期运行。
Secondly unless there is something else going on in your code you can't look for files in a folder using the 'in' keyword, you'll need to construct a full filepath by concatenating the filename and the folder path.其次,除非您的代码中发生了其他事情,否则您无法使用“in”关键字在文件夹中查找文件,您需要通过连接文件名和文件夹路径来构建完整的文件路径。
Try this approach:试试这个方法:
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)
The file names inside the csv must have an extension. csv 内的文件名必须有扩展名。 If they don't, then you should use filename = os.path.join(cop_folder, i + '.jpg')
如果他们没有,那么你应该使用 filename = os.path.join(cop_folder, i + '.jpg')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.