【问题标题】:Python: Select and move file based on criteria in a directoryPython:根据目录中的条件选择和移动文件
【发布时间】:2019-05-30 02:10:01
【问题描述】:

我有大约 10 分钟的视频,只是提取到每一帧中,所以我的文件夹中有超过 100,000 张图像,并将它们从 1 重命名为 100,000。现在我想从 1 到 100,000 张图像中选择每 30 张中的 1 张并将它们移动到另一个文件夹。例如:1、31、61、91、121、151、181等。

这是我目前的代码:

import os
import shutil

PATH = './Folder1/'
DEST = './Folder2/'

file = 1

for file in os.listdir(PATH):
    file = file + 30
    shutil.copyfile(PATH, DEST)

但它给了我以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-b08091703697> in <module>
      9 # Get a list of files in the current working directory
     10 for file in os.listdir(PATH):
---> 11     file = file + 30
     12     shutil.copyfile(PATH, DEST)

TypeError: can only concatenate str (not "int") to str

提前感谢您的帮助!

【问题讨论】:

    标签: python python-3.x file file-io shutil


    【解决方案1】:

    您的错误说您需要先将 int 转换为 str 才能将它们相加。你可以使用

    file = file + str(30)
    

    然后稍后改进您的原始代码。

    或者你可以在下面使用我的想法。

    for idx in range(1, 100000, 30):
       shutil.copyfile(PATH + str(idx), DEST)    
    

    【讨论】:

    • 找到问题根源的最佳答案。
    • 感谢您的快速回复。我刚刚尝试了所有答案,但它显示 PermissionError: [Errno 13] Permission denied: './Folder2/'。
    • 以下文档:docs.python.org/3/library/shutil.html#shutil.copyfile 我想我们可以试试:shutil.copyfile(PATH + str(idx), DEST + str(idx))
    【解决方案2】:

    试试下面的代码

    PATH = '/Folder1/'
    DEST = './Folder2/'
    l = os.listdir(PATH)
    file = 1
    
    for file in l[::30]:
        shutil.copyfile(PATH, DEST)
    

    【讨论】:

      【解决方案3】:

      for file in os.listdir(PATH) 中的“file”是一个字符串,所以file = file + 30 无效。 你应该试试:

      import os
      import shutil
      
      PATH = './Folder1/'
      DEST = './Folder2/'
      
      filenames = os.listdir(PATH)
      
      for i in range(1, len(filenames), 30):
          shutil.copyfile(PATH + filenames[i], DEST)
      

      【讨论】:

        猜你喜欢
        • 2016-09-14
        • 1970-01-01
        • 1970-01-01
        • 2019-05-07
        • 1970-01-01
        • 2014-02-28
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        相关资源
        最近更新 更多