python - 根据文本列表Python将文件移动到不同的文件夹中
问题描述
我是 python 新手,我一直在尝试简化我在日常工作中执行的手动任务,我有一个文本文件,其中包含由空行分隔的文件名列表,如下所示:
fileName1
fileName2
fileName3
fileName4
fileName5
fileName6
fileName7
fileName8
fileName9
fileName10
fileName11
fileName12
所有这些文件都在一个文件夹中,我想找到每组文件并将它们移动到单独的文件夹中,新文件夹的名称应该是每个组的第一个文件的名称。
我正在做我的研究,我发现如何使用os
和shutil
模块分别执行每个步骤,但我找不到将它们连接在一起并制作漂亮脚本的方法,我能从你们那里得到的任何帮助都会很棒,谢谢!!
解决方案
这是一个可以做到这一点的小脚本。我做了两个假设:
- 带有文件列表的文件存储在与源文件相同的目录中
- 最后一个文件后有一个空行,因此脚本可以抓取最后一个组
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",""))
推荐阅读
- c++ - C/C++ VS 代码 - 无法开始调试。启动管道程序时出错
- sql - 如何从下面的代码中获得正确的结果?
- python - 查找 Redis 中值最高的前 N 个键
- google-cloud-platform - 端点可以在云上调用多个后端服务吗?
- batch-file - 如何正确获取字符“!” 当延迟扩展处于活动状态时变为变量值?
- wordpress - 如何修改非 WordPress 文档的 HTACCESS 文件
- cmake - 使用 brew 安装时,Cmake 无法使用 pkg_search_module 找到“cairo”
- python - Do not change signature of methods when subclassing?
- codenameone - 如何将 CSS 覆盖到 Codenameone 中的主要资源主题上
- java - LWJGL 中 MemoryStack 的使用