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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With