首页 > 解决方案 > 根据文本列表Python将文件移动到不同的文件夹中

问题描述

我是 python 新手,我一直在尝试简化我在日常工作中执行的手动任务,我有一个文本文件,其中包含由空行分隔的文件名列表,如下所示:

fileName1
fileName2 
fileName3
fileName4

fileName5
fileName6
fileName7
fileName8

fileName9
fileName10 
fileName11
fileName12  

所有这些文件都在一个文件夹中,我想找到每组文件并将它们移动到单独的文件夹中,新文件夹的名称应该是每个组的第一个文件的名称。

我正在做我的研究,我发现如何使用osshutil模块分别执行每个步骤,但我找不到将它们连接在一起并制作漂亮脚本的方法,我能从你们那里得到的任何帮助都会很棒,谢谢!!

标签: pythonpython-3.x

解决方案


这是一个可以做到这一点的小脚本。我做了两个假设:

  1. 带有文件列表的文件存储在与源文件相同的目录中
  2. 最后一个文件后有一个空行,因此脚本可以抓取最后一个组
import os
from shutil import move
from itertools import groupby

#Where the files are originally stored
src_path = "C:\\temp\\src\\"

#Where the group folders will go
dest_path = "C:\\temp\\dest\\"

#Open up the file containing the list of files
with open(src_path + "list_of_files.txt") as txt:
    lines = txt.readlines() #Read the file

    #Split the contents of the file based on the newline character "\n"
    i = (list(g) for _, g in groupby(lines, key='\n'.__ne__))
    list_of_groups = [a + b for a, b in zip(i, i)]

    #Iterate through each group
    for group in list_of_groups:
        folder_name = dest_path + group[0].replace("\n","") + "\\"
        
        if not os.path.exists(folder_name):
            #Create a folder for each group if it doesn't already exist
            os.mkdir(folder_name)
        
        #Move over each file in the group. The last element in the group is a newline character
        for file in group:
            if file != "\n":
                move(src_path + file.replace("\n",""),folder_name + file.replace("\n",""))


推荐阅读