Home >Backend Development >Python Tutorial >How Can I Move Files in Python Using `os.rename()`, `os.replace()`, and `shutil.move()`?

How Can I Move Files in Python Using `os.rename()`, `os.replace()`, and `shutil.move()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 12:12:151000browse

How Can I Move Files in Python Using `os.rename()`, `os.replace()`, and `shutil.move()`?

Moving Files in Python

Python offers several methods to accomplish the task of moving files, analogous to the mv command in Unix-like systems. These methods include:

  • os.rename()
  • os.replace()
  • shutil.move()

All three share a consistent syntax:

import os
import shutil

os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

Here are some important considerations when moving files:

  • The filename ("file.foo") must be specified in both the source and destination paths. If it differs, the file will be renamed as well as moved.
  • The parent directory of the destination path must exist prior to moving the file.
  • On Windows systems, the destination path cannot specify an existing file, as this will raise an exception. However, os.replace() will silently overwrite existing files.
  • shutil.move typically invokes os.rename for file moves within the same disk. However, when the destination and source are on different disks, shutil.move copies the file and then deletes the original.

The above is the detailed content of How Can I Move Files in Python Using `os.rename()`, `os.replace()`, and `shutil.move()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn