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

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

Mary-Kate Olsen
Release: 2024-12-25 04:44:10
Original
802 people have browsed it

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

Moving Files in Python: The Equivalent of mv

Python offers several functions to accomplish the task of moving a file, akin to the mv command in the terminal. These functions include os.rename(), os.replace(), and shutil.move().

Function Syntax

All three functions employ the same 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

Key Considerations

  • The filename ("file.foo") must be included in both the source and destination arguments. If it differs, the file will be renamed and moved.
  • The directory for the new file must exist beforehand.
  • On Windows, a file with the intended name must not exist when using os.rename(), or an exception will occur. os.replace(), however, will overwrite existing files without prompting.
  • shutil.move typically delegates the task to os.rename(). If the source and destination are on different disks, it copies the file and deletes the original instead.

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

source:php.cn
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