首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不工作:将在.csv文件中找到的文件复制到列表中,然后如果在特定文件夹中复制到目标文件夹

不工作:将在.csv文件中找到的文件复制到列表中,然后如果在特定文件夹中复制到目标文件夹
EN

Stack Overflow用户
提问于 2020-04-25 09:26:54
回答 1查看 147关注 0票数 0

我几乎是在从这个线程(Python - copying specific files from a list into a new folder)复制代码,但是无法让它正常工作,也看不出出了什么问题。有洞察力吗?

csv文件在第一列中有图像名(即image.png),在下一列中具有重要/不重要的名称,但尚未使用。现在在10个文件上测试一下。这10个文件在我想要复制的文件夹中。

代码语言:javascript
复制
    # ----------------------------------------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!')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-25 15:49:04

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

代码语言:javascript
复制
    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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61423523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档