[英]Move files into different folders based on a text list Python
I´m new to python and I´ve been trying to simplify a manual task that I do on my daily bases, I have a text file with a list of file names separated in groups by a blank line, like this:我是 python 的新手,我一直在尝试简化我在日常工作中执行的手动任务,我有一个文本文件,其中包含由空行分隔的文件名列表,如下所示:
fileName1
fileName2
fileName3
fileName4
fileName5
fileName6
fileName7
fileName8
fileName9
fileName10
fileName11
fileName12
All of this files are in one folder and I want to find each group of files and move them into separate folders the name of the new folders should be the name of the first file of each group.所有这些文件都在一个文件夹中,我想找到每组文件并将它们移动到单独的文件夹中,新文件夹的名称应该是每个组的第一个文件的名称。
I´m doing my research and I found how to do each step separately using os
and shutil
modules but I can´t find a way to join them together and make a beautiful script, any help that I can get from you guys will be awesome, thanks!!我正在做我的研究,我发现如何使用os
和shutil
模块分别执行每个步骤,但我找不到将它们连接在一起并制作漂亮脚本的方法,我能从你们那里得到的任何帮助都会很棒, 谢谢!!
Here's a little script that can do that.这是一个可以做到这一点的小脚本。 I've made two assumptions:我做了两个假设:
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",""))
When reading a file you can look up characters.读取文件时,您可以查找字符。 Blank spaces have a newline character as represented by \n .空格有一个换行符,由\n表示。
import os
filepath1 = os.getcwd() # current working directory
filepath2 = "path\\to\\where\\you\\want\\dir"
filename = os.path.join(filepath1,"yourfilename.txt")
dirName = []
groupName = "filegroup"
idx = 1
newPath = ""
init = True
file = open(filename, "r")
for line in file:
if init == True: # initial folder
newPath = os.path.join(filepath2,groupName + str(idx))
os.mkdir(newPath)
dirName.append(groupName)
init = False
if line == "\n": # line in file is empty
idx += 1
newName = groupName + str(idx)
dirName.append(newName)
newPath = filepath2 + dirName[idx-1]
os.mkdir(newPath)
else:
os.mkdir(os.path.join(newPath,line.rstrip()))
file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.