Hello,

I've got this directory with files that contain a number in their file name. I need to check what the number is and then I need to move the file to a different directory.

Right now I'm using shutil to do this, but for some reason it copies the file instead of moving it.

Here's a piece of my code:

import shutil, re, glob
checked_pages =  glob.glob('C:/dir1/checked*.txt')
if checked_pages != []:
	for file in checked_pages:
		# Find out the file number
		filepattern = re.compile(r'(checked)([0-9]+?)(.txt)')
		if re.search(filepattern, file): # Is this necessary or can I leave the if-statement out?
			found = re.search(filepattern, file)
			filenumber = found.group(2)
		else:
			pass # Once again: is this necessary?
		dest_file = 'C:/dir2/moved' + filenumber + '.txt'
		shutil.move(file, dest_file)
                # And here I'm gonna use the filenumber to do something else.

Does any of you have any idea why shutil doesn't remove the file from the source directory after copying it?

Thank you very much in advance!

Doris

I would write it this way

import re, glob, os
# compile the pattern only once and separately
# avoid unnecessary groups in the pattern
# escape the dot character
checkedpattern = re.compile(r'checked([0-9]+?)\.txt')

# avoid 'file' as a variable name
for src_file in glob.glob('C:/dir1/checked*.txt'):
    # Find out the file number
    found = checkedpattern.search(src_file)
    if not found:
        continue
    filenumber = found.group(1)
    dest_file = 'C:/dir2/moved%s.txt' % filenumber
    # simply use os.rename (according to the python doc)
    os.rename(src_file, dest_file)

Edited 6 Years Ago by Gribouillis: n/a

Hello Gribouillis,

Thanks for your reply. I guess you can tell that I'm still fairly new to Python ;)
Your code looks much nicer, but it still doesn't remove the src_file for some reason. Do you have any idea why?

Doris

Edited 6 Years Ago by DancingDana: misspelled name

Hello Gribouillis,

Thanks for your reply. I guess you can tell that I'm still fairly new to Python ;)
Your code looks much nicer, but it still doesn't remove the src_file for some reason. Do you have any idea why?

Doris

I don't understand. When I run the code in my linux system, it runs well and removes the src files. It could be a problem of file permissions. You should check the permissions of your files. Before that, you can check if you can move one of the files manually with a cut and paste operation.

Edited 6 Years Ago by Gribouillis: n/a

Hello Gribouillis,

Thanks again for your reply. I spent ages looking at the code and I finally found the problem. It's in a completely different part of the code. The files do get moved, they just get created again after moving, so that's why it looks like the moving doesn't work. Problem solved!

Doris

This question has already been answered. Start a new discussion instead.