简体   繁体   English

连续将文件从单个目录移动到三个单独的文件夹-Python

[英]Move files from a single directory to three separate folders, consecutively - Python

Python user here getting the basics of the os/shutil libraries. 此处的Python用户获得了os / shutil库的基础知识。

I'm trying to move files within a single directory folder (Test) to three, separate folders (01-Folder, 02-Folder and 03-Folder) consecutively. 我试图将单个目录文件夹(测试)中的文件连续移动到三个单独的文件夹(01文件夹,02文件夹和03文件夹)。 This meaning that the 1st file in the directory is placed into 01-Folder, the 2nd file is placed into 02-Folder, and the 3rd is placed into 03-Folder. 这意味着目录中的第一个文件放置在01文件夹中,第二个文件放置在02文件夹中,第3个文件放置在03文件夹中。 From here forward (whether or not there are 5 or 1000 files in Test), the process repeats itself where 4 would go back into 01-Folder, 5 would go into 02-Folder, 6 into 03, 7 into 01, 8 into 02, 9 into 03 - and so forth. 从这里开始(测试中是否有5或1000个文件),该过程会重复进行,其中4将返回01文件夹,5将进入02文件夹,6进入03,7进入01,8进入02 ,将9变成03-依此类推。

These three folders can be placed within the original directory or placed on the outside. 这三个文件夹可以放在原始目录中,也可以放在外面。 The key here is just the order - they need to be pulled in some sort of ordered loop. 这里的关键只是顺序-它们需要以某种有序循环的形式被拉出。

What I'm having problems with is the file selection once I'm inside of the directory. 我遇到的问题是进入目录后选择文件。 How would I traverse through each file, and send them to their respective folders while maintaining the order that they were in originally? 我将如何遍历每个文件,然后将它们发送到各自的文件夹,同时保持它们原来的顺序?

import os
import shutil

# Original folder
original = ('C:\\Users\\Vision3\\Desktop\\Test') 

# Destination folders
path1 = ('C:\\Users\\Vision3\\Desktop\\01-Folder')
path2 = ('C:\\Users\\Vision3\\Desktop\\02-Folder')
path3 = ('C:\\Users\\Vision3\\Desktop\\03-Folder')

# Traverse original
for root, subdirs, files, in os.walk(original):
    for file in files:
        # Select the first three files? Grey area here ...
        for x in range(0,2):
            # Move these first three files to 01-Folder?
            shutil.move(x, path1)

You can set the destination path to a dictionary and then use this logic. 您可以将目标路径设置为字典,然后使用此逻辑。

import os
import shutil  

path = "C:\\Users\\USERNAME\\Desktop\\A\\"
path1 = 'C:\\Users\\USERNAME\\Desktop\\01-Folder'
path2 = 'C:\\Users\\USERNAME\\Desktop\\02-Folder'
path3 = 'C:\\Users\\USERNAME\\Desktop\\03-Folder'

d = {1: path1, 2: path2, 3: path3}
c = 1
for root, dirnames, filenames in os.walk(path):
    for filename in filenames:
        filePathVal =  os.path.join(root, filename)
        shutil.move(filePathVal, d[c])
        c += 1
        if c > 3:
            c = 1

Note: Tested in python2.7 注意: 已在python2.7中测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM