Home > Backend Development > Python Tutorial > How Can I Move Files in Python?

How Can I Move Files in Python?

Mary-Kate Olsen
Release: 2024-12-11 10:48:12
Original
705 people have browsed it

How Can I Move Files in Python?

Moving Files in Python

In Python, you can move a file using various methods, including:

os.rename()

import os

os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
Copy after login

os.replace()

import os

os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
Copy after login

shutil.move()

import shutil

shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
Copy after login

These methods all have the same syntax. The first argument is the path to the current file, and the second argument is the path to the new destination.

Considerations

  • The filename ("file.foo") must be included in both the source and destination arguments. If it differs between the two, the file will be renamed as well as moved.
  • The directory within which the new file is being created must already exist.
  • On Windows, a file with that name must not exist or an exception will be raised.
  • shutil.move simply calls os.rename in most cases. However, if the destination is on a different disk than the source, it will instead copy the source file and then delete it.

The above is the detailed content of How Can I Move Files in Python?. 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