1

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"]
1
  • You shouldn't need python for this. Commented Oct 21, 2019 at 2:25

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing the code adrianp. It was really helpful. Works perfectly fine.
1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.