Issue
I want to copy a specific file from different directories to another directory. Each of the directories has several files with the same extension. I want to copy one particular file from each directory to another folder and rename the file with indexes. Here is an example of my current root directory tree.
root--Dir1--subDir1--subDir2
| |--x.bmp
| |--y.bmp
| |-t.txt
Dir2--subDir1--subDir2
| |--x.bmp
| |--y.bmp
| |-t.txt
Dir3--subDir1--subDir2
| |--x.bmp
| |--y.bmp
| |-t.txt
I want to copy only the x.bmp file to the other directory. And my desired directory will be like given example tree below.
NEWDIR
|--x1.bmp
|--x2.bmp
|--x3.bmp
.
.
I wrote a sample code block by taking the help from other posts, but it is giving me error. Here I posted code snippets and error.
import os
import shutil
import glob
root_dir = 'oldDir'
dest_dir = 'NewDir'
os.listdir(root_dir)
for folder in os.listdir(root_dir):
folder_path = os.path.join(root_dir, folder)
if os.path.isdir(folder_path):
for subfolder in os.listdir(folder_path):
subfolder_path = os.path.join(root_dir, folder, subfolder)
for subfolder2 in os.listdir(subfolder_path):
subfolder2_path = os.path.join(root_dir, folder, subfolder,subfolder2)
for filename in os.listdir(subfolder2_path):
if filename == 'X.bmp':
file_path = os.path.join(root_dir, folder, subfolder, subfolder2,filename)
for i in filename:
filename = 'X.bmp'%(i,)
dest_path = os.path.join(dest_dir, filename)
shutil.copy(file_path, dest_path)
print("Copied ", file_path, "to", dest_path)
The error messages that I got
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6448/526909518.py in <module>
22 #filename+=1
23 for i in filename:
---> 24 filename = 'X.bmp'%(i,)
25 dest_path = os.path.join(dest_dir, filename)
26 shutil.copy(file_path, dest_path)
TypeError: not all arguments converted during string formatting
I got similar question in the stackoverflow, but answer did not help me. I appreciate help in this regard.
Solution
You can use glob
for finding the files you need. A sample is below
import glob, pathlib, shutil
root_dir = r"C:/drive/samples"
target_dir = pathlib.Path(r"C:/drive/samples/D2")
copy_files = list(glob.glob(f"{root_dir}/**/*.bmp",recursive=True))
index =1
for file in copy_files:
file = pathlib.Path(file)
target_file = target_dir / f"{file.stem}{index}{file.suffix}"
shutil.copyfile(file, target_file)
index+=1
May be there are more improvements to this. But this is one of the easy way to it,
Answered By - Kris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.