This question is definitely a duplicate of this.
Using os
is fine, but my preference is pathlib's Path module - it handles windows and linux / unix paths real well, so makes for easy cross platform utilization. It has various methods already built into it, so you "don't have to" import glob
and os
modules for moving files, checking if they exist, etc:
With the help of this answer from the question linked above, we can do this:
from pathlib import Path
import shutil
path = Path(r"/opt/data/input/IP10/")
abs_path = path.absolute().parent # the path to the `Path` directory's parent directory
# there is a glob method as well.
# rglob is the recursive method.
for f in path.rglob('**/*.*'):
dir_name = f.parent.stem # the parent directory's name
name = f.with_name(f"{dir_name}_{f.name}").name # the new name of the file
shutil.copy(f, f'{abs_path}/IP10_for_decoder/copy/{name}')
Some nice examples of what can be done with Path:
path = Path("./kansas.png")
path.stem # -> kansas
path.name # -> kansas.png
path.suffix # -> .png - if no "." in the filename, this will return an empty string
path.with_suffix(".jpg") # -> kansas.jpg
path.with_stem("texas") # -> texas.png
path.with_name("texas.jpg") # -> texas.jpg
path.absolute() # -> returns "/opt/data/input/IP10/kansas.png"
path.exists() # -> returns a boolean if it exists
path.parent # -> on absolute paths returns the full path to the parent directory
path.unlink() # deletes the file
path.touch() # "touches" the file
# replace and rename are a little hard to distinguish the difference between, imo, but both return a new path
path = path.replace(Path("/new/location/new_name.jpg"))
path = path.rename("new_file_name.jpg") # will rename the file
I thought there was a copy method for pathlib's Path, but nope.
There are a myriad of other operations - .parts
splits the path into a list of directories and the filename that make up the path, you can read and write bytes and text to and from a file, .chmod
a file or directory, and so on. Here is the documentation.