Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script to move specific files from one folder to another

Tags:

python-2.7

I am trying to write a script (python 2.7) that will use a regex to identify specific files in a folder and move them to another folder. When I run the script, however, the source folder is moved to the target folder instead of just the files within it.

import os, shutil, re

src = "C:\\Users\\****\\Desktop\\test1\\"
#src = os.path.join('C:',  os.sep, 'Users','****','Desktop','test1\\')
dst = "C:\\Users\\****\\Desktop\\test2\\"
#dst = os.path.join('C:',  os.sep, 'Users','****','Desktop','test2')

files = os.listdir(src)
#regexCtask = "CTASK"
print files
#regex =re.compile(r'(?<=CTASK:)')


files.sort()

#print src, dst

regex = re.compile('CTASK*')

for f in files:
    if regex.match(f):
        filescr= os.path.join(src, files)
        shutil.move(filesrc,dst) 
        #shutil.move(src,dst) 

So basically there are files in "test1" folder that I want to move to "test2", but not all the files, just the ones that contain "CTASK" at the beginning.

The **** in the path is to protect my work username.

Sorry if it is messy, I am still trying a few things out.

like image 296
iNeedScissors61 Avatar asked Mar 10 '23 01:03

iNeedScissors61


1 Answers

You need to assign path to exact file (f) to filescr variable on each loop iteration, but not path to files (files - is a list!)

Try below code

import os
from os import path
import shutil

src = "C:\\Users\\****\\Desktop\\test1\\"
dst = "C:\\Users\\****\\Desktop\\test2\\"

files = [i for i in os.listdir(src) if i.startswith("CTASK") and path.isfile(path.join(src, i))]
for f in files:
    shutil.copy(path.join(src, f), dst)
like image 118
Andersson Avatar answered May 13 '23 04:05

Andersson