📜  shutil move overwrite - Python (1)

📅  最后修改于: 2023-12-03 15:34:58.682000             🧑  作者: Mango

Shutil Move Overwrite - Python

The "shutil" module in Python provides a way to move files from one location to another. The "move" function in the module can be used for the same purpose. However, if the destination location already has a file with the same name as the source file, the "move" function will raise an error.

To overwrite the file at the destination location, we can use the "shutil.move()" function with the "copy_function" parameter set to "shutil.copy2". This will copy the file from the source location to the destination location, overwriting the existing file if necessary.

Here's the code snippet for moving a file with overwrite option:

import shutil

src = "/path/to/source/file"
dst = "/path/to/destination/folder"

shutil.move(src, dst, copy_function=shutil.copy2)

Here, "src" is the path to the source file and "dst" is the path to the destination folder. The "copy_function" parameter is set to "shutil.copy2" which ensures that the file is copied with all its metadata intact.

Note: If the destination folder doesn't exist, the "shutil.move()" function will rename the file with the destination folder name.

In summary, using "shutil.move()" with the "copy_function" parameter set to "shutil.copy2" is a way to move a file from one location to another, overwriting the destination file if necessary.