如何在python中一次移动一个文件到多个文件夹

1zmg4dgp  于 2022-10-30  发布在  Python
关注(0)|答案(2)|浏览(128)

我只是想知道你对我能做什么的见解,因为我已经迷路2天了。我正在尝试做的是将一个文件从1个文件夹移动到5个文件夹,一次一个。以下是我目前得到的信息。

import os
import shutil

# path

source = 'C:/Users/folder/Downloads/Files/test'

destination = ['C:/Users/folder/Downloads/Files/test1',
    'C:/Users/folder/Downloads/Files/test2',
    'C:/Users/folder/Downloads/Files/test3',
    'C:/Users/folder/Downloads/Files/tes',
    'C:/Users/folder/Downloads/Files/test5']

def countItems():
    global totalfiles
    global copiedfiles
    totalfiles = 0
    copiedfiles = 1
    for item in os.listdir(source):
        totalfiles += 1

# get total items

countItems()

# get Destination

while(totalfiles != 0):
    for dst in destination:
        for items in os.listdir(source):
            s = os.path.join(source, items)
            d = os.path.join(dst, items)
            if os.path.isfile(d):
                checker = 'Copy of'
                filename, filext = os.path.splitext(items)
                finalF = checker + filename + filext
                newd = os.path.join(dst, finalF)
                os.rename(s, newd)
                countItems()
            else:
                shutil.move(s, d)
                countItems()

我试图将所有的文件平均分布在整个5目标文件夹。

ccrfmcuu

ccrfmcuu1#

你有很多额外的无意义的操作文件名,但没有旋转通过目的地。这是什么你问:

import os
import shutil

source = 'C:/Users/folder/Downloads/Files/test'

destination = [
    'C:/Users/folder/Downloads/Files/test1',
    'C:/Users/folder/Downloads/Files/test2',
    'C:/Users/folder/Downloads/Files/test3',
    'C:/Users/folder/Downloads/Files/tes',
    'C:/Users/folder/Downloads/Files/test5']

for item in os.listdir(source):
    dst = destination.pop(0)
    s = os.path.join(source, item)
    d = os.path.join(dst, 'Copy of '+item)
    os.rename(s, d)
    destination.append( dst )
1tuwyuhd

1tuwyuhd2#

为了一次将一个目录的所有项目复制到另一个目录,您可以使用2个内置方法:

两种方法的通用代码段:dirs_exist_ok
source = r"C:/Users/USERNAME/OneDrive/Desktop/Dev/Rough/Source/"

destinations = [
    r"C:/Users/USERNAME/OneDrive/Desktop/Dev/Rough/Destination_1/",
    r"C:\Users\USERNAME\OneDrive\Desktop\Dev\Rough\CLI_Dev\Destination_2",
    r"C:/Users/USERNAME/OneDrive/Desktop/Dev/Projects/Destination_3/",
    r"C:/Users/USERNAME/OneDrive/Personal/Destination_4/",
    r"C:/Users/USERNAME/OneDrive/Backups/Destination_5/"
]

方法1:目录_实用程序.复制树()

import distutils.dir_util as du

for dest in destinations:
    if not os.path.exists(dest): os.mkdir(dest)         # Create dir if doesn't exist
    du.copy_tree(source, dest)                          # Copies all items to another dir

方法二:shutil.复制树()

import shutil

for dest in destinations:
    shutil.copytree(source, dest, dirs_exist_ok = True) # Copies all items to another dir

dirs_exist_ok确保在dir已存在的情况下不会抛出错误
利用这些方法,你不必复制每个项目一个接一个到每个目录

相关问题