How to move files to and from folders using shutil and os in python?

83 Views Asked by At

So, I'm looking to move some images from my downloads folder to my pictures folder (Windows 11), but I am continually being met with errors. Here is my code:

import shutil 
import os 
source = r"C:\Users\zaner\Downloads\AI.jpg\"
path = r"C:\Users\zaner\Downloads\AI.jpg\"
print("Before Copy: ")
print(os.listdir(path))
perm = os.stat(source).st_mode
print("File Permission mode:", perm, "\n")


destination = r"C:\Users\zaner\OneDrive\Pictures\Camera Roll\"

dest = shutil.copy(source, destination)

I have tried using every kind of slash, including back, front, and none at all. I even used double at one point. I am met with either not a real directory errors or an unterminated string literal. I am stumped tbh, so any and all help would be greatly appreciated.

2

There are 2 best solutions below

5
sahasrara62 On BEST ANSWER

you need to mention files to which need to be relocated

import shutil
import os 
source = r"C:\Users\zaner\Downloads\AI.jpg\"
path = r"C:\Users\zaner\Downloads\AI.jpg\"
files = os.listdir(path)
for file in files:
    new_source = source + file
    new_path = path + file
    shutil.copy(new_source, new_path)

or you can simply do

import os
source = r"C:\Users\zaner\Downloads\AI.jpg\"
path = r"C:\Users\zaner\Downloads\AI.jpg\"

os.system(f"cp source{*} path")
1
nisakova On

in case if you are looking for multiple .jpg file

source = r"C:\Users\zaner\Downloads\"
destination = r"C:\Users\zaner\OneDrive\Pictures\Camera Roll\"
for file in os.listdir(source):
    if file.endswith('.jpg'):
        shutil.copy(source + file, destination)