简体   繁体   中英

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

Python user here getting the basics of the os/shutil libraries.

I'm trying to move files within a single directory folder (Test) to three, separate folders (01-Folder, 02-Folder and 03-Folder) consecutively. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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