pythondirectoryshutilpython-os

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


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.


Solution

  • 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")