Link to home
Start Free TrialLog in
Avatar of 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

Given a directory structure like this:


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.
    ['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


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

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