Python provides different methods in order to move files via a Python script. By using Python single files or multiple files can be moved in the same directory or a different directory.
Move File with rename()
The os
module provides the rename()
function in order to rename specified files and folders. Even though it may seem the rename and move are different actually the rename provides the same results as the move(). We can use the os.rename() function in order to move files. The source or original file is provided as the first parameter the destination path and the name is provided as the second parameter.
import os
os.rename("/home/ismail/db.txt","/mnt/db.txt")
Alternatively, we can specify the source and destination paths as variables.
import os
source_path = "/home/ismail/"
destination_path= "/mnt/"
file_name= "db.txt"
os.rename(source_path+file_name,destination_path+file_name)
Move File with replace()
Another function to move files is the replace() . The replace() function is provided via the os module. The replace() is simply created to replace the specified destination file. Keep in mind that if the destination file is overwritten even if it exists.
import os
os.replace("/home/ismail/db.txt","/mnt/db.txt")
Alternatively, we can specify the source and destination paths as variables.
import os
source_path = "/home/ismail/"
destination_path= "/mnt/"
file_name= "db.txt"
os.replace(source_path+file_name,destination_path+file_name)
Move File with move()
The original function to move files is the shutil.move()
function. This move() function is provided via the shutil
module. As with previous methods, the move() function accepts the source path and file name as the first parameter and the destination path with the file name as the second parameter.
import shutil
shutil.move("/home/ismail/db.txt","/mnt/db.txt")
Alternatively, we can specify the source and destination paths as variables.
import shutil
source_path = "/home/ismail/"
destination_path= "/mnt/"
file_name= "db.txt"
shutil.move(source_path+file_name,destination_path+file_name)