简体   繁体   中英

Shutil.move doesn't move folder, but contents of folder

I'm writing a script to reorganise a large data set so that it'll be mostly compatible with a database system we're currently implementing. Most of our data is currently not organised in any meaningful way, although some folders are already marked in the way the script will. As such I've implemented a case to catch this.

Let's call this case "INFO". In all but the first instance of this my script works fine, finds the "INFO_example[2,3,4....]" folder at the top level, and moves it to a new "INFO" folder that contains all of these examples. However, for some reason in the first instance "INFO_example1" it instead takes the contents of the folder and dumps them in "INFO" instead.

I've attempted to debug the problem, but can't see any differences between the first and any other instances. The folder path also doesn't appear any differently.

file_path = join(self.path, file)
try:
    move(file_path, self.info_path)
except shutil.Error:
    print("Trying to move", file_path, " didn't work")

I'm a little stumped to what's actually going on.

I'd expect the "INFO_example1" folder to behave as all the others do, and just be moved into the top level "INFO" folder.

Currently, it's contents are moved into "INFO", and the "INFO_example1" folder appears to be deleted.

My print message also never fires.

So, the issue was that shutil.move would look at say "INFO_example1" and try to move it to "INFO", notice that "INFO" did not exist, and so would create it and put the contents of "INFO_example1" in to it instead of creating another folder within and then moving the contents into there.

Due to the nature of the script creating "INFO" before trying to move files caused more issues, however, if I updated the section that moves the "INFO_example" folders, to look like:

    file_path = join(self.path, file)
        try:
            if not isdir(self.info_path):
                mkdir(self.info_path)
            move(file_path, self.info_path)
        except shutil.Error:
            print("Trying to move", file_path, " didn't work")

Checking whether the "INFO" directory exists or not, and if not creating it but only when I'm attempting to move an "INFO_example" style folder gives the expected behaviour, at least for myself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM