shutil.move()
shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on os.rename() semantics.
Example:
Directory Used
Python3
# Python program to explain shutil.move() method # importing os module import os # importing shutil module import shutil # path path = '/home/nikhil/Desktop/' # List files and directories # in 'C:/Users/Rajnish/Desktop/w3wiki' print ( "Before moving file:" ) print (os.listdir(path)) # Source path source = '/home/nikhil/Desktop/new' # Destination path destination = '/home/nikhil/Desktop/new2' # Move the content of # source to destination dest = shutil.move(source, destination) # List files and directories # in "C:/Users / Rajnish / Desktop / w3wiki" print ( "After moving file:" ) print (os.listdir(path)) # Print path of newly # created file print ( "Destination path:" , dest) |
Output:
10 Python File System Methods You Should Know
While programming in any language, interaction between the programs and the operating system (Windows, Linux, macOS) can become important at some point in any developer’s life. This interaction may include moving files from one location to another, creating a new file, deleting a file, etc.