Link to home
Start Free TrialLog in
Avatar of delic8te
delic8te

asked on

Code for moving files from one location to another

I am having difficulties  in creating some code which does the following:

1) Searches through a table for files/path names  that exist
2) If they do exist, i.e. a path name exists, its takes the name of the file and moves it to another location - for e.g a file caled invoice.html which resided at c:mydocs\ now has to be copied and moved to a folder called c:\invoices.

Can anyone give me some example code that I can do that does this.
Thanks in advance

delic8te :)
Avatar of RichieHindle
RichieHindle

Given a directory structure like this:

c:\temp\ee\input
c:\temp\ee\output\invoices
c:\temp\ee\output\other

where there are files called invoice.html and something.txt in c:\temp\ee\input, this will
move invoice.html to the 'invoices' directory and something.txt to the 'other' directory:

import os
from glob import glob
from os.path import join, split

# ROOT is where the input and output directories live.
ROOT = r'C:\temp\ee'

# The FILES table describes which files to find and where to put them.
# It allows wilcards, and defines a default rule for files that don't match.
FILES = [
    ['invoice*.html', 'invoices'],
    ['*', 'other'],
]

for pattern, destination in FILES:
    for pathname in glob(join(ROOT, 'input', pattern)):
        filename = split(pathname)[1]
        move_to = join(ROOT, 'output', destination, filename)
        print pathname, "->", move_to
        os.rename(pathname, move_to)
Avatar of delic8te

ASKER

thanks - but can u explain the for loop code to me - thanks
ASKER CERTIFIED SOLUTION
Avatar of RichieHindle
RichieHindle

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial