Oct-28-2021, 04:07 PM
(This post was last modified: Oct-28-2021, 04:08 PM by DeaD_EyE.
Edit Reason: forgotten the imports
)
The old functions in
The Path object gives you more Abstraction.
os
and os.path
are very low level and are hard to use.The Path object gives you more Abstraction.
import shutil from pathlib import Path def move_files(sources, destination, extensions=None): # converting the str to a Path object # if it's already a Path object, it # will return also a Path object destination = Path(destination) # you've more than one source directory # so iterating over this list with possible str or Path objects for source in sources: # here the same conversion to Path objects happens like before source = Path(source) # checking if it's on the same file system # if this is the case, the file can be renamed # otherwise the file must be copied same_filesystem = source.stat().st_dev == destination.stat().st_dev for source_path in source.iterdir(): # continue if source_path is not regular file if not source_path.is_file(): # continue -> back to the top of the inner for-loop continue # checking first if extension is provided # and if the suffix is in extensions # if the first condition is not True, the # second condition is not evaluated if extensions and source_path.suffix not in extensions: continue dst_path = destination / source_path.name # checking if the file on the target already exists # and skipping it if it's the case if dst_path.exists(): continue # if the file is on the same filesystem # then the file could be renamed # otherwise the slow copy operation must be used if same_filesystem: # rename operation on same fs source_path.rename(dst_path) else: # move operation if it's not the same fs # move does two operations: copy and then delete the # old file shutil.move(source_path, dst_path)For example,
move_files(["A", "B", "C"], "Q")
will rename/move files from directories A, B, C (one level deep) to directory Q. move_files(["A", "B", "C"], "Q", [".jpg", ".png"])
will move only jpg
and png
files.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!