Ali Ajaz
Ali Ajaz

Reputation: 59

How to copy multiple files in multiple folders using Python

I have multiple files in one folder (1_ppt.csv, 2_ppt.csv, 3_ppt.csv,...). I have their corresponding empty folders as (SIM1, SIM2, SIM3,...). I want to copy the 1_ppt.csv to SIM1 folder, 2_ppt.csv to SIM2 folder,...so on. I tried it using cmd command, it works; however, it requires the file and folder names to be same, so its not useful. I will really appreciate if I can get a python solution to this.

Used these cmd commands so far.

[for %i in (*) do mkdir "%~ni"]
[for %i in (*) do move "%i" "%~ni"]

Upvotes: 1

Views: 1600

Answers (2)

Arundeep Chohan
Arundeep Chohan

Reputation: 9969

import os
import shutil
src=""
src_files = os.listdir(src)
i=0
for file_name in src_files:
   full_file_name = os.path.join(src, file_name)
   if os.path.isfile(full_file_name)& full_file_name.endswith("_ppt.csv"):
     i+=1
     dirName="SIM"+str(i)
     try:
     # Create target Directory
       os.mkdir(dirName)
     except FileExistsError:

    if not os.path.exists(dirName):
       os.mkdir(dirName)  

    shutil.copy(full_file_name, dirName)

Put this python file into where you want your SIM folders to go and put the src of where your one folder is.

Upvotes: 1

adrianp
adrianp

Reputation: 1019

Assuming that the file tree looks like this:

|--PPTs
|   |--1_ppt.csv
|   |--2_ppt.csv
|   .
|   .
|   |--n_ppt.csv
|--SIM1
|--SIM2
.
.
|--SIMN
|--script.py

You can do the following:

from pathlib import Path
import shutil

base_path = Path.cwd()
ppt_path = base_path.joinpath('PPTs')
for ppt in ppt_path.iterdir():
    ppt_num = ppt.name.split('_')[0]
    out_path = base_path.joinpath(f'SIM{ppt_num}', ppt.name) # e.g. SIM1/ppt_1.csv
    shutil.copy(ppt, out_path)

You can also create directories on the fly by modifying the for loop:

for ppt in ppt_path.iterdir():
    ppt_num = ppt.name.split('_')[0]
    out_folder = base_path.joinpath(f'SIM{ppt_num}')
    # Add this line
    out_folder.mkdir(exist_ok=True)
    out_path = out_folder.joinpath(ppt.name) # e.g. SIM1/ppt_1.csv
    shutil.copy(ppt, out_path)

Upvotes: 1

Related Questions