Home > Back-end >  How to move file from folder A to folder B in python?
How to move file from folder A to folder B in python?

Time:10-17

What am I doing wrong and what do i need to improve?

import os
source = "C:\\Users\\User\\Desktop\\ala.txt"
destination = "C:\\Users\\User\\Desktop\\zzz.txt"

try:
    if os.path.exists(destination):
        print("There is already a file there")
    else:
        os.replace(source,destination)
        print(source " was moved")
except FileNotFoundError:
    print(source " was not found")

CodePudding user response:

Could you try this one?

import os

os.rename("C:\\Users\\User\\Desktop\\ala.txt", "C:\\Users\\User\\Desktop\\zzz.txt")

CodePudding user response:

You can try importing shutil and calling shutil.move(source,destination). The shutil module provides functions for moving files, as well as entire folders.

CodePudding user response:

You can also try using the shutil package like this :

import os
import shutil

source = r"C:\Users\omkar\Desktop\source"
destination = r"C:\Users\omkar\Desktop\destination"

allfiles = os.listdir(source)

for f in allfiles:

    shutil.move(source  r"\\"   f, destination)
  • Related