How to Move a File in Python

How to move a file in Python?

os.rename(), os.replace(), or shutil.move()

All employ the same 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")

Note that you must include the file name (file.foo) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved.

Note also that in the first two cases the directory in 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, but os.replace() will silently replace a file even in that occurrence.

As has been noted in comments on other answers, 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 and then delete the source file.

Moving all files from one directory to another using Python

Try this:

import shutil
import os

source_dir = '/path/to/source_folder'
target_dir = '/path/to/dest_folder'

file_names = os.listdir(source_dir)

for file_name in file_names:
shutil.move(os.path.join(source_dir, file_name), target_dir)

how to move and overwrite file to another folder in python?

You can't do it in a single line, you'll have to do:

import os, shutil

if os.path.isfile(os.path.join(d_folder, min_file)):
os.remove(os.path.join(d_folder, min_file))

d_folder = shutil.move(min_file, d_folder)
print("File is moved successfully to: ", d_folder)

This checks if the file already exists, and deletes it if so, then moves the new file to there.



Related Topics



Leave a reply



Submit