不起作用:将在.csv文件中找到的文件复制到列表中,然后如果在某些文件夹中,则复制到目标文件夹中

问题描述 投票:0回答:1

我几乎是从此线程(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!')
python arrays csv copy filepath
1个回答
0
投票

下面的代码可能有助于解决您面临的问题-


    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://docs.python.org/3/library/os.html#os.walk

© www.soinside.com 2019 - 2024. All rights reserved.