Copy a file with a too long path to another directory in Python

前端 未结 3 569
余生分开走
余生分开走 2020-12-14 10:20

I am trying to copy files on Windows with Python 2.7, but sometimes this fails.

shutil.copyfile(copy_file, dest_file)

I get the following I

3条回答
  •  醉话见心
    2020-12-14 10:37

    Maybe do something like this:

    path = "some/really/really/long/path/more/than/255/chars.txt"
    
    def copyFile(path, dest, relative=0):
        if len(path) > 255:
            if not os.sep in path:
                raise SomeException()
            moveTo, path = path.split(os.sep, 1)
            os.chdir(moveTo)
            copyFile(path, dest, relative + 1)
        else:
            path_base = ['..'] * relative
            path_rel = path_base + [dest]
            shutil.copyfile(path, os.path.join(*path_rel))
    

    This is tested, and does work... however, if the destination is more than 255 chars, you would be back in the same boat. In that case, you may have to move the file several times.

提交回复
热议问题