Как я могу переместить файлы в другой каталог и в соответствующие папки, сопоставив имя файла с именем папки?

У меня есть файлы, которые я хотел бы переместить в разные папки в зависимости от их имени файла. примеры имен файлов:

296_A_H

import shutil
import os

#filepath to files
source = 'C:\\Users\\Desktop\\test folder'

#filepath to destination folders
dest1 = 'C:\\Users\\Desktop\\move file\\296_A_H_1'
dest2 = 'C:\\Users\\Desktop\\move file\\296_A_H_2'
dest3 = 'C:\\Users\\Desktop\\move file\\296_A_H_10'
dest4 = 'C:\\Users\\Desktop\\move file\\296_A_H_20'

files = [os.path.join(source, f) for f in os.listdir(source)]

#move files to destination folders based on file path and name
for f in files:
    if (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_1_")):
        shutil.copy(f,dest1)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_2_")):
        shutil.copy(f,dest2)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_10")):
        shutil.copy(f, dest3)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_20")):
        shutil.copy(f, dest4)
1_20070405.pdf

296_A_H_10

import shutil
import os

#filepath to files
source = 'C:\\Users\\Desktop\\test folder'

#filepath to destination folders
dest1 = 'C:\\Users\\Desktop\\move file\\296_A_H_1'
dest2 = 'C:\\Users\\Desktop\\move file\\296_A_H_2'
dest3 = 'C:\\Users\\Desktop\\move file\\296_A_H_10'
dest4 = 'C:\\Users\\Desktop\\move file\\296_A_H_20'

files = [os.path.join(source, f) for f in os.listdir(source)]

#move files to destination folders based on file path and name
for f in files:
    if (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_1_")):
        shutil.copy(f,dest1)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_2_")):
        shutil.copy(f,dest2)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_10")):
        shutil.copy(f, dest3)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_20")):
        shutil.copy(f, dest4)
20070405.pdf

296_A_H_2

import shutil
import os

#filepath to files
source = 'C:\\Users\\Desktop\\test folder'

#filepath to destination folders
dest1 = 'C:\\Users\\Desktop\\move file\\296_A_H_1'
dest2 = 'C:\\Users\\Desktop\\move file\\296_A_H_2'
dest3 = 'C:\\Users\\Desktop\\move file\\296_A_H_10'
dest4 = 'C:\\Users\\Desktop\\move file\\296_A_H_20'

files = [os.path.join(source, f) for f in os.listdir(source)]

#move files to destination folders based on file path and name
for f in files:
    if (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_1_")):
        shutil.copy(f,dest1)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_2_")):
        shutil.copy(f,dest2)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_10")):
        shutil.copy(f, dest3)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_20")):
        shutil.copy(f, dest4)
20070405.pdf

296_A_H_20

import shutil
import os

#filepath to files
source = 'C:\\Users\\Desktop\\test folder'

#filepath to destination folders
dest1 = 'C:\\Users\\Desktop\\move file\\296_A_H_1'
dest2 = 'C:\\Users\\Desktop\\move file\\296_A_H_2'
dest3 = 'C:\\Users\\Desktop\\move file\\296_A_H_10'
dest4 = 'C:\\Users\\Desktop\\move file\\296_A_H_20'

files = [os.path.join(source, f) for f in os.listdir(source)]

#move files to destination folders based on file path and name
for f in files:
    if (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_1_")):
        shutil.copy(f,dest1)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_2_")):
        shutil.copy(f,dest2)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_10")):
        shutil.copy(f, dest3)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_20")):
        shutil.copy(f, dest4)
20070405.pdf

Соответствующие имена папок:

296_A_H_1

296_A_H_2

296_A_H_10

296_A_H_20

Я хочу переместить файлы в правильную папку на основе имени файла. Например, файл 296_A_H_1

import shutil
import os

#filepath to files
source = 'C:\\Users\\Desktop\\test folder'

#filepath to destination folders
dest1 = 'C:\\Users\\Desktop\\move file\\296_A_H_1'
dest2 = 'C:\\Users\\Desktop\\move file\\296_A_H_2'
dest3 = 'C:\\Users\\Desktop\\move file\\296_A_H_10'
dest4 = 'C:\\Users\\Desktop\\move file\\296_A_H_20'

files = [os.path.join(source, f) for f in os.listdir(source)]

#move files to destination folders based on file path and name
for f in files:
    if (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_1_")):
        shutil.copy(f,dest1)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_2_")):
        shutil.copy(f,dest2)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_10")):
        shutil.copy(f, dest3)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_20")):
        shutil.copy(f, dest4)
20070405.pdf должен находиться в папке 296_A_H_1. Вот код, который у меня есть до сих пор:

import shutil
import os

#filepath to files
source = 'C:\\Users\\Desktop\\test folder'

#filepath to destination folders
dest1 = 'C:\\Users\\Desktop\\move file\\296_A_H_1'
dest2 = 'C:\\Users\\Desktop\\move file\\296_A_H_2'
dest3 = 'C:\\Users\\Desktop\\move file\\296_A_H_10'
dest4 = 'C:\\Users\\Desktop\\move file\\296_A_H_20'

files = [os.path.join(source, f) for f in os.listdir(source)]

#move files to destination folders based on file path and name
for f in files:
    if (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_1_")):
        shutil.copy(f,dest1)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_2_")):
        shutil.copy(f,dest2)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_10")):
        shutil.copy(f, dest3)
    elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_20")):
        shutil.copy(f, dest4)

Этот код работает, но мне нужно переместить 400 файлов в разные папки и написать сотни операторов elif. Как я могу это сделать, сопоставив имя файла с папкой назначения и используя Shutil, чтобы скопировать файл в эту папку? Я только начинаю изучать Python, поэтому любая помощь здесь будет очень признательна!


person Zfrieden    schedule 19.04.2017    source источник


Ответы (1)


Как насчет этого? Вы в основном сопоставляете места назначения с файлами, которые должны идти в эти места назначения, используя проверку членства в строке (т.е. if d in x). Это, конечно, предполагает, что все файлы, которые нужно переместить, начинаются с папки source, а все места назначения находятся в одной и той же папке ('C:\\Users\\Desktop\\move file').

source = 'C:\\Users\\Desktop\\test folder'

dests = os.listdir('C:\\Users\\Desktop\\move file')

# Map each destination to the files that should go to that destination
dest_file_mapping = {d: {os.path.join(source, x
                      for x in os.listdir(source) if d in x} for d in dests}

for dest, files in dest_file_mapping.items():
    for f in files:
        shutil.copy(f, dest)
person blacksite    schedule 19.04.2017
comment
когда я использую этот метод, я получаю ошибку разрешения: [Errno 13] Отказано в доступе: 'C:\\Users\\\\Desktop\\Target test\\296_A_H_1' - person Zfrieden; 19.04.2017
comment
Это потому, что вы обращаетесь к файлу, который требует прав администратора для открытия/редактирования/изменения. Когда вы открываете командную строку для запуска скрипта Python, рассмотрите возможность щелчка правой кнопкой мыши и выбора «Запуск от имени администратора». - person Michael Molter; 05.06.2017