迭代并删除目录中的文件

2024-06-25 04:36:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个目录中遍历一些文件,然后将它们复制到一个特定的位置(基于它们的初始名称),然后从当前目录中删除它们。但我发现下一个文件被删除后,我就把它们一起删除了。如何解决: 这是我的代码:

import os
import csv
import glob,fnmatch, shutil ,time

ftp_directory = 'C:\\CIRP\\Velocidata\\Test\\'
IFIND_LOCATION = 'C:\\CIRP\\Velocidata\\Test2\\'

# Getting the list of all files
for root, dirs, files in os.walk(ftp_directory):
    # Filtering for group names that are 'Inprogress'
    groups_beingworked = []
    for name in files:
      #Getting the exception in the below line in the second iteration 
      group = name[0:name.lower().find('infile')]
      for loop2 in files:
       if (loop2[:len(group)].lower() == group):
         groups_beingworked.append(loop2)
       for loop3 in groups_beingworked:
              shutil.copy2(os.path.join(root,loop3) ,IFIND_LOCATION)
              print ('Deleting the file : ' + loop3)
              #File removed from the FTP location through a ftp conn created elsewhere
              ftpconn.delete(os.path.join(root, loop3))

我尝试查看的示例文件列表是:

^{pr2}$

Tags: 文件thenameinimportforosgroup