Reputation: 29
I am trying to move files and folders from directory to another. I am currently facing two issues.
Do you know what might be missing to do this. I could add an or
statement statement with startswith
but would like to see if there is a better way to do this.
import os
from os import path
import shutil
src = "C:/Users/test/documents/"
dst = "C:/Users/test/Documents/test"
files = [i for i in os.listdir(src) if i.startswith("C") and \
path.isfile(path.join(src, i))]
for f in files:
shutil.move(path.join(src, f), dst)
Upvotes: 1
Views: 100
Reputation: 248
This will go through the source directory, create any directories that do not yet exist in the destination directory, and move the files from the source to the destination directory:
(As I understand it, this is what you want)
import os
import shutil
src = "C:/Users/test/documents/"
dst = "C:/Users/test/documents/test"
for src_dir, dirs, files in os.walk(src):
dst_dir = src_dir.replace(src, dst, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.move(src_file, dst_dir)
Upvotes: 1