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

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

Mary-Kate Olsen
Release: 2024-12-21 14:03:10
Original
1034 people have browsed it

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

How to Move Files using Python Functions

Python includes multiple methods for moving files, analogous to the "mv" command in Unix-like systems. These functions include os.rename(), os.replace(), and shutil.move().

Syntax:

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")
Copy after login

Usage:

  • The filename ("file.foo") must be included in both the source and destination arguments. If the filenames are different, the file will be renamed during the move.
  • The destination directory must already exist.
  • Windows systems require that a file with the same name does not already exist at the destination, or an exception will be raised. However, os.replace() will silently replace an existing file.
  • shutil.move generally behaves similarly to os.rename. However, if the destination is on a different disk than the source, it will copy the file and then delete the original.

The above is the detailed content of How to 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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template