how to move files in directories in group of 3
Question:
I have 60 files and 20 folders in same directory.
I want to move first three files to the first folder, next three files to another folder and so on.
Basically move 60 files in group of three into 20 folders.
I made a list including path for each file, but for the part that move them to folders I’m not sure what to do:
import os
import shutil
path = r'C:.......est Files'
destination = r'C:.......est Files
paths = []
for root, dirs, file in os.walk(path):
for name in file:
paths.append(os.path.join(root,name))
Answers:
import os
import shutil
# Get the list of files in the current directory
files = os.listdir()
# Filter the list of files to only include regular files
files = [f for f in files if os.path.isfile(f)]
# Create a list of folders to move the files to
folders = [f"folder{i+1}" for i in range(20)]
# Loop over each group of three files
for i in range(0, len(files), 3):
# Create a path for each file in the group
file_paths = [os.path.join(os.getcwd(), files[j]) for j in range(i, i+3)]
# Move the group of files to the next folder
for path in file_paths:
shutil.move(path, folders[i // 3])
I have 60 files and 20 folders in same directory.
I want to move first three files to the first folder, next three files to another folder and so on.
Basically move 60 files in group of three into 20 folders.
I made a list including path for each file, but for the part that move them to folders I’m not sure what to do:
import os
import shutil
path = r'C:.......est Files'
destination = r'C:.......est Files
paths = []
for root, dirs, file in os.walk(path):
for name in file:
paths.append(os.path.join(root,name))
import os
import shutil
# Get the list of files in the current directory
files = os.listdir()
# Filter the list of files to only include regular files
files = [f for f in files if os.path.isfile(f)]
# Create a list of folders to move the files to
folders = [f"folder{i+1}" for i in range(20)]
# Loop over each group of three files
for i in range(0, len(files), 3):
# Create a path for each file in the group
file_paths = [os.path.join(os.getcwd(), files[j]) for j in range(i, i+3)]
# Move the group of files to the next folder
for path in file_paths:
shutil.move(path, folders[i // 3])