我几乎是在从这个线程(Python - copying specific files from a list into a new folder)复制代码,但是无法让它正常工作,也看不出出了什么问题。有洞察力吗?
csv文件在第一列中有图像名(即image.png),在下一列中具有重要/不重要的名称,但尚未使用。现在在10个文件上测试一下。这10个文件在我想要复制的文件夹中。
# ----------------------------------------IMPORT PACKAGES -------------------
import os
import shutil
import csv
# ------------------------------------copy IMAGES using --------------
# ----------------------GET PATHS----------------------------------------
folderpath = os.getcwd() # /home/ubuntu/Deep-Learning/FinalProject/data_random
destination = '/home/ubuntu/Deep-Learning/FinalProject/data_subset'
# ------------------LIST OF IMAGE NAMES----------------------------------
filestofind = []
with open("labels_test.csv", "r") as f:
filestofind = [x[0] for x in csv.reader(f) if x]
print(filestofind)
# successfully gets list of image names
# [' image1.png', ' image2.png', ...'image10.png]
# ------FIND IMAGE IN FOLDER AND COPY AND MOVE TO DESTINATION FOLDER----
for filename in filestofind:
print('filename1',filename) #filename1 image1.png - looks ok
for file in folderpath(filename):
print('filename2',filename) #It is seeing this as a string and
#iterating through the string
# says it is not callable
# filename2 /
# filename2 h
# filename2 o
# filename2 m
# expected to look for filename1 above in the folderpath
if os.path.isfile(filename):
shutil.copy(filename, destination)
else:
print('file does not exist: filename')
print('All done!')发布于 2020-04-25 15:49:04
下面的代码可能有助于解决您所面临的问题-
all_files = [f for f in os.listdir(folderpath) if os.path.isfile(os.path.join(folderpath, f))]
# This returns all the files you have in your search directory
files_to_copy = [x for x in filestofind if x in all_files]
# This returns the common files you want to copy
for file_to_copy in files_to_copy:
shutil.copy(file_to_copy, destination)PS:您可以在# ------FIND IMAGE IN FOLDER AND COPY AND MOVE TO DESTINATION FOLDER----"之后复制上面的内容
参考:
https://stackoverflow.com/questions/61423523
复制相似问题