深度阅读

How to move a file in Python using shutil.move()?

作者
作者
2023年08月22日
更新时间
10.82 分钟
阅读时间
0
阅读量

To move a file in Python, you can use the shutil.move() method from the shutil library. This method takes two parameters: the source file path and the destination file path. Here is an example:

import shutil

src = "/path/to/file.txt"
dst = "/path/to/newlocation/file.txt"
shutil.move(src, dst)

This example moves the file located at /path/to/file.txt to /path/to/newlocation/file.txt.

One benefit of using shutil.move() over os.rename() is that shutil.move() can handle cases where the source and destination files are on different filesystems, whereas os.rename() cannot. Additionally, shutil.move() allows you to specify a new filename for the file being moved, whereas os.rename() only allows you to change the path.

Note that if the destination file already exists, shutil.move() will overwrite it without warning. Also, if an exception occurs during the move operation, the source file may be left in an inconsistent state.

Using shutil.move() is useful when you need to move a file from one location to another in your file system.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。