Abdullah
Abdullah

Reputation: 53

Python rglob("*") vs glob("*)

I am trying to move a bunch of files with "V1.2" in the name to an archive folder. It seems to be working fine with the following code:

for folder in copyPath.glob("*"):
    for subfolder in folder.glob("*"):
        for content in subfolder.glob("*"):
            if "V1.2" in content.name:
                shutil.move(content ,Path(subfolder,"Archive"))

However, the following code with rglob("*V1.2*"), python just creates an "Archive" named extentionless file into the archive folder. Why is that?

for file in copyPath.rglob("*V1.2*"):
    shutil.move(file,Path(file.parent,"Archive"))

Regards, AS

Upvotes: 1

Views: 6286

Answers (1)

Green 绿色
Green 绿色

Reputation: 2916

You state that the following code creates a file named "Archive" in the archive folder:

for file in copyPath.rglob("*V1.2*"):
    shutil.move(file,Path(file.parent,"Archive"))

shutil.move only moves your files into a directory if the directory already exists. Otherwise, it'll move (rename) your file. I guess that Path(file.parent, "Archive") is not a directory, so every file matching the condition is moved into a file called "Archive", each file overwriting the previous one.

The fix should be simple:

for file in copyPath.rglob("*V1.2*"):
    target = Path(file.parent, "Archive")
    if target.is_file():
        raise ValueError(f"Invalid directory: {target} is a file!")  # safety check to avoid overwriting files and data loss

    if not target.is_dir():
        target.mkdir(parents=True)  # <- this should solve your problem

    shutil.move(file, target)

Upvotes: 2

Related Questions